Quicksort in Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

/**
*
*/

/**
* @author asharda
*
*/
public class qsort {

static ArrayList<Integer> list = new ArrayList<Integer>();

/**
* @param args
*/
public static void main(String[] args) {

Scanner in = new Scanner(System.in);
System.out.println(“Enter size of the array”);
int size = in.nextInt();
System.out.println(“Enter ” + size + “elements”);
for (int i = 0; i < size; i++) {
list.add(in.nextInt());

}
qsort(0, list.size() – 1);
display();
in.close();
}

public static void qsort(int low, int high) {
int i = low, j = high;
int pivot = list.get(low + (high – low) / 2);
while (i <= j) {
while (list.get(i) < pivot) {
i++;
}
while (list.get(j) > pivot) {
j–;
}
if (i <= j) {
Collections.swap(list, i, j);
i++;
j–;

}

}// end of main while loop
if (low < j)
qsort(low, j);
if (i < high)
qsort(i, high);
}// end of qsort

public static void display() {
for (int i : list)
System.out.println(i);
}
}

Advertisements

About qainterviews

Software Geek,QA Expert,Blogger
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s