Created
April 10, 2014 17:25
-
-
Save jayeshsolanki93/10404303 to your computer and use it in GitHub Desktop.
QuickSort in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Scanner; | |
class QuickSort { | |
private static Scanner sc; | |
public static void main(String args[]) { | |
sc = new Scanner(System.in); | |
System.out.println("Enter no of terms"); | |
int n = sc.nextInt(); | |
System.out.println("Enter the terms"); | |
int arr[] = new int[n]; | |
for (int i = 0; i < n; i++) | |
arr[i] = sc.nextInt(); | |
System.out.println("The unsorted array is:"); | |
System.out.println(Arrays.toString(arr)); | |
sort(arr, 0, arr.length - 1); | |
System.out.println("The sorted array is:"); | |
System.out.println(Arrays.toString(arr)); | |
} | |
static void sort(int arr[], int start, int end) { | |
if (start < end) { | |
int pIndex = partition(arr, start, end); | |
sort(arr, start, pIndex - 1); | |
sort(arr, pIndex + 1, end); | |
} | |
} | |
static int partition(int arr[], int start, int end) { | |
int pivot = arr[end]; | |
int pIndex = start; | |
for (int i = start; i < end; i++) { | |
if (arr[i] <= pivot) { | |
swap(arr, i, pIndex); | |
pIndex++; | |
} | |
} | |
swap(arr, pIndex, end); | |
return pIndex; | |
} | |
static void swap(int arr[], int x, int y) { | |
int temp = arr[x]; | |
arr[x] = arr[y]; | |
arr[y] = temp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment