Write a program to Sort an array in ascending order using quicksort


This program is implementing QuickSort algorithm to sort an array of integers in ascending order.

  • The QuickSort method takes three arguments: the array to be sorted, the first index f and the last index l of the subarray to be sorted.
  • Inside the method, the pivot is selected as the first element of the subarray. The i and j variables are initialized to f and l respectively. Then, a while loop runs until i is less than j. Inside this loop, another while loop runs until a[i] is greater than a[pivot] and i is less than l. Similarly, another while loop runs until a[j] is less than or equal to a[pivot] . If i is less than j, then swap the values of a[i] and a[j].
  • After the inner while loop, swap the value of a[pivot] with a[j]. Then recursively call the QuickSort method with arguments as the original array, first index and j-1, and again with the original array, j+1 and last index.
  • In the main method, an integer array a is declared with some elements. Then, QuickSort method is called with arguments as the array, first index and last index. After sorting, the elements of the array are printed in ascending order.

Source Code

public class Ascending_Quicksort
{
	static void QuickSort(int a[], int f, int l)
	{
		int pivot = 0;
		int temp = 0;
		int i = 0;
		int j = 0;
 
		if (f < l)
		{
			pivot = f;
			i = f;
			j = l;
 
			while(i < j)
			{
				while(a[i] <= a[pivot] && i < l)
				{
					i = i + 1;
				}
				while(a[j] > a[pivot])
				{
					j = j - 1;
				}
 
				if(i < j)
				{
					temp = a[i];
					a[i] = a[j];
					a[j] = temp;
				}
			}
 
			temp = a[pivot];
			a[pivot] = a[j];
			a[j] = temp;
 
			QuickSort(a, f, j - 1);
			QuickSort(a, j + 1, l);
		}
	}
 
	public static void main(String[] args)
	{
		int i = 0;
		int j = 0;
		int t = 0;
		int a[] = {2, 65, 23, 13, 18, 30, 46, 17, 52, 78};
 
		QuickSort(a, 0, a.length - 1);
 
		System.out.println("Sorted Array in Ascending Order ..");
		i = 0;
		while(i < 10)
		{
			System.out.print(a[i] + " ");
			i = i + 1;
		}
	}
}

Output

Sorted Array in Ascending Order ..
2 13 17 18 23 30 46 52 65 78

Example Programs