Answer to Question #216836 in Java | JSP | JSF for harsh

Question #216836

Consider a pile of coins. You have given ‘n’ coins of different sizes and you want to sort the pile so that smaller coins are on the top of larger ones. The only “operation” you are allowed to perform is- take top ‘k’ coins together, and place them back to the pile upside down


1
Expert's answer
2021-07-13T13:36:28-0400
import java.io.*;
 
class PileCoins {
    static void flip(int arr[], int i)
    {
        int temp, start = 0;
        while (start < i)
        {
            temp = arr[start];
            arr[start] = arr[i];
            arr[i] = temp;
            start++;
            i--;
        }
    }
 
    static int getMax(int arr[], int n)
    {
        int x, i;
        for (x = 0, i = 0; i < n; ++i)
            if (arr[i] > arr[x])
                x = i;
        return x;
    }
    static int coinSort(int arr[], int n)
        for (int c = n; c > 1; c--)
        {
            int x = getMax(arr, c);
            if (x != c-1)
            {
                flip(arr, x);
                flip(arr, c-1);
            }
        }
        return 0;
    }
 
    static void printArray(int arr[], int size)
    {
        for (int i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
        System.out.println("");
    }
 
    public static void main (String[] args)
    {
        int arr[] = {1,2,3,4,5,6};
        int n = arr.length;
         
        coinSort(arr, n);
         
        System.out.println("Sorted Array: ");
        printArray(arr, n);
    }
}
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS