Wednesday, September 10, 2014

Quick Sort

private static class Quicksort { int array[]; int size; public Quicksort(int n) { size = n; //create array with size n+1 array = new int[n + 1]; //asign value into the array for (int i = 0; i < n; i++) { array[i] = (int) Math.round(Math.random() * 89 + 10); } //set the last element as big value array[n] = 99999; } public int partition(int p, int q) { int i = p; int j = q + 1; // Get the pivot element from the middle of the list int pivot = array[p]; // Divide into two lists do { // If the current value from the left list is smaller then the pivot // element then get the next element from the left list do { i++;// As we not get we can increase i } while (array[i] < pivot); // If the current value from the right list is larger then the pivot // element then get the next element from the right list do { j--;// As we not get we can increase j } while (array[j] > pivot); // If we have found a values in the left list which is larger then // the pivot element and if we have found a value in the right list // which is smaller then the pivot element then we exchange the values. if (i < j) { swap(i, j); } } while (i < j); //swap the pivote element and j th element swap(p, j); return j; } private void swap(int p, int j) { //exachage the elements int temp = array[p]; array[p] = array[j]; array[j] = temp; } public void quicksort() { // Recursion quicksort(0, size - 1); } public void quicksort(int p, int q) { int j; if (p < q) { // Divide into two lists j = partition(p, q); // Recursion quicksort(p, j - 1); quicksort(j + 1, q); } } public void print() { //print the elements of array for (int i = 0; i < size; i++) { System.out.print(array[i] + " | "); } System.out.println(); } public static void main(String args[]) { Quicksort q = new Quicksort(15); System.out.println("Before Sort <<<<<<<<<<<<<<<<<<<<<"); q.print(); q.quicksort(); System.out.println("After Sort > > > > > > > > > > > >"); q.print(); System.out.println("=======+============+=======+============+=======+============"); Quicksort q2 = new Quicksort(125); System.out.println("Before Sort <<<<<<<<<<<<<<<<<<<<<"); q2.print(); q2.quicksort(); System.out.println("After Sort > > > > > > > > > > > >"); q2.print(); System.out.println("=======+============+=======+============+=======+============"); Quicksort q3 = new Quicksort(5); System.out.println("Before Sort <<<<<<<<<<<<<<<<<<<<<"); q3.print(); q3.quicksort(); System.out.println("After Sort > > > > > > > > > > > >"); q3.print(); } } }

No comments:

Post a Comment

advertisement