quick sort descending order java code example

Example 1: java sort array descending

Integer[] cubes = new Integer[] { 8, 27, 64, 125, 256 };
Arrays.sort(cubes, Collections.reverseOrder());

Read more: https://www.java67.com/2016/07/how-to-sort-array-in-descending-order-in-java.html#ixzz6MX60xZLb

Example 2: quicksort in code

// A full c++ quicksort algorithm no bs
// quicksort in code

#include <iostream>

using namespace std;

void QuickSort(int arr[], int start, int end);
int Partition(int arr[], int start, int end);
void SwapArrMem(int arr[], int a, int b);

int main()
{

	int arr[4]; //change the size of the array to your desired array size

	cout << "enter " << sizeof(arr) / sizeof(arr[0]) << " numbers. press enter after input" << endl;

	for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
	{
		
		cin >> arr[i];
	}

	cout << endl << "The sorted numbers are:" << endl << endl;



	QuickSort(arr, 0, sizeof(arr) / sizeof(arr[0]) - 1);

	for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
	{
		cout << arr[i] << endl;
	}

}

void QuickSort(int arr[], int start, int end)
{
	if (start >= end) return;

	int index = Partition(arr, start, end);
	QuickSort(arr, start, index - 1);
	QuickSort(arr, index + 1, end);
}

int Partition(int arr[], int start, int end)
{
	int pivotindex = start;
	int pivotvalue = arr[end];
	for (int i = start; i < end; i++)
	{
		if (arr[i] < pivotvalue)
		{
			SwapArrMem(arr, i, pivotindex);
			pivotindex++;
		}
	}
	SwapArrMem(arr, pivotindex, end);
	return pivotindex;
}

void SwapArrMem(int arr[], int a, int b)
{
	int temp = arr[a];
	arr[a] = arr[b];
	arr[b] = temp;
}

Example 3: analysis of quick sort

T(n) = 2*T(n/2) + n                        // T(n/2) = 2*T(n/4) + (n/2)    

        = 2*[ 2*T(n/4) + n/2 ] + n
	= 22*T(n/4) + n + n
	= 22*T(n/4) + 2n                       // T(n/4) = 2*T(n/8) + (n/4)

	= 22*[ 2*T(n/8) + (n/4) ] + 2n
	= 23*T(n/8) + 22*(n/4) + 2n
	= 23*T(n/8) + n + 2n
	= 23*T(n/8) + 3n

	= 24*T(n/16) + 4n
	and so on....

	= 2k*T(n/(2k)) + k*n      // Keep going until: n/(2k) = 1  <==> n = 2k    

	= 2k*T(1) + k*n
	= 2k*1 + k*n
	= 2k + k*n               // n = 2k
	= n + k*n
	= n + (lg(n))*n
        = n*( lg(n) + 1 )
       ~= n*lg(n))

Tags:

Java Example