In this tutorial, you will learn how to implement quick sorting in Java. The quick Sort program algorithm is a very fast sorting algorithm and is one of the common sorting algorithm which is asked in exams.
Source code for Quick Sort Java Program
public class QuickSort { public static void main(String args[]) { int[] x = {597, 21, 523, 1378, 243, 774, 14, 93, 510}; System.out.println("Unsorted list: "); display(x); quickSort(x, 0, x.length-1); } private static void quickSort(int x[], int lb, int ub) { int j=0; if (lb>=ub) return; j = partition(x, lb, ub); System.out.println("After partitioning array from index "+(lb+1)+ " to"+(ub+1)+":"); display(x); quickSort(x, lb, j-1); quickSort(x, j+1, ub); } private static int partition(int x[], int lb, int ub) { int a, down, temp, up; a = x[lb]; up = ub; down = lb; while (down < up) { while(x[down]<=a && down<up) down++; while(x[up]>a) up--; if (down < up) { temp = x[down]; x[down] = x[up]; x[up] = temp; } } x[lb] = x[up]; x[up] = a; return up; } private static void display(int x[]) { for (int i=0; i<x.length; i++) System.out.print(x[i] + " "); System.out.println("\n"); } }
Output of Quick Sort Java Program

0 comments:
Post a Comment