Saturday, July 19, 2014

Quick Sort Algorithm using Java

Quick Sort works on Divide and Conquer algorithm. Here, given array is divided into two parts, left and right. and both array are being sorted individually. After then we combine and will have sorted array.

How it works:
  1. Pick up any element in Array. ex. middle element of array. we called this one as Pivot.
  2. All elements which are smaller than Pivot are placed in one array and All elements which are larger than pivot are placed in another array
  3. Using recursion sort both array using quicksort
  4. Combine array as mentioned below.
Java Program using Quick sort algorithm:

package com.anuj.algorithms;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 *
 * @author Anuj
 * @source goldenpackagebyanuj.blogspot.com
 */
public class QuickSort {

    public static void main(String[] args) {
        QuickSort quickSort = new QuickSort();
        List<Integer> input = quickSort.generateRandomNumbers(10);

        System.out.println("Before Sorting : " + input);
        System.out.println("After Sorting : " + quickSort.quickSort(input));
    }

    private List<Integer> generateRandomNumbers(int n) {
        List<Integer> input = new ArrayList<>();
        Random random = new Random();

        for (int i = 0; i < n; i++) {
            input.add(random.nextInt(n * 10));
        }
        return input;
    }

    private List<Integer> quickSort(List<Integer> input) {
        if (input.size() <= 1) {
            return input;
        }

        int middle = (int) Math.ceil((double) input.size() / 2);
        int pivot = input.get(middle);

        List<Integer> less = new ArrayList<>();
        List<Integer> greater = new ArrayList<>();

        for (int i = 0; i < input.size(); i++) {
            if (input.get(i) <= pivot) {
                if (i == middle) {
                    continue;
                }
                less.add(input.get(i));
            } else {
                greater.add(input.get(i));
            }
        }

        return concate(quickSort(less), pivot, quickSort(greater));
    }

    private List<Integer> concate(List<Integer> less, int pivot, List<Integer> greater) {
        List<Integer> list = new ArrayList<>();

        for (Integer i : less) {
            list.add(i);
        }
        list.add(pivot);
        for (Integer j : greater) {
            list.add(j);
        }
        return list;
    }
}


Output :
run:
Before Sorting : [34, 41, 82, 50, 33, 61, 97, 54, 84, 31]
After Sorting : [31, 33, 34, 41, 50, 54, 61, 82, 84, 97]
BUILD SUCCESSFUL (total time: 0 seconds)

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/