CodesJava

Easy learning with example program codes

Java quick sort algorithm example


Sorting algorithm

A sorting algorithm is a way to put elements of a list in a certain order. The most-used orders are numerical order and lexicographical order. Efficient sorting is important for optimizing the use of other algorithms (like search and merge algorithms) which require input data to be in sorted lists. It is also often useful for canonicalizing data and for producing human-readable output.

The output must satisfy following two conditions:

  • The output is in no decreasing order i.e.each element is no smaller than the previous element according to the desired total order.
  • The output is a reordering of elements but with all of the original elements of the input.

Quicksort sort

Quicksort is a divide and conquer algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays.

Quicksort steps:

  • Pick an element, called a pivot, from the array.
  • Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
  • Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.

The base case of the recursion is arrays of size zero or one, which are in order by definition, so they never need to be sorted.

Example

package com.codesjava;
 
public class Test {
     public static int[] insertionSort(int data[]) {
	int temp;
        for (int i = 1; i < data.length; i++) {
            for(int j = i ; j > 0 ; j--){
                if(data[j] < data[j-1]){
                    temp = data[j];
                    data[j] = data[j-1];
                    data[j-1] = temp;
                }
            }
        }
       return data;
     }
 
     private static void printNumbers(int[] data) {          
        for (int i = 0; i < data.length; i++) {
            System.out.print(data[i]);
            if(i != data.length-1){
            	System.out.print(", ");
            }
        }
        System.out.println("\n");
     }
 
	public static void main(String args[]){
		int[] data = {8, 2, 4, 9, 3, 6}; 
		//Print array elements
		printNumbers(data);
		int[] sortedDate = insertionSort(data);  
		//Print sorted array elements
		printNumbers(sortedDate);
	}
}

Output

8, 2, 4, 9, 3, 6
 
2, 3, 4, 6, 8, 9


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap