Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.Scanner;
- public class QuickSort {
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- System.out.println("Enter number of elements: ");
- int N = scan.nextInt();
- int[] arr = new int[N];
- for (int i = 0; i < N; i++) {
- System.out.print("Enter element " + i + " :");
- arr[i] = Integer.parseInt(scan.next());
- }
- //print before//
- System.out.println("BEFORE SORT: " + Arrays.toString(arr));
- quickSort(arr, 0, N -1);
- //print after//
- System.out.println("AFTER SORT: " + Arrays.toString(arr));
- }//end of main//
- public static void quickSort(int[] arr, int low, int high){
- if(low < high){
- int pi = partition(arr, low, high);
- quickSort(arr, low, pi - 1);
- quickSort(arr, pi + 1, high);
- }
- }//end of quickSort//
- public static int partition(int[] arr, int low, int high){
- int pivot = arr[high];
- int i = low - 1;
- for (int j = low; j < high; j++) {
- if(arr[j] < pivot){
- i++;
- //swap//
- int temp = arr[j];
- arr[j] = arr[i];
- arr[i] = temp;
- }
- }
- //put the pivot element at the right position//
- int temp = arr[high];
- arr[high] = arr[i + 1];
- arr[i + 1] = temp;
- return i + 1;
- }//end of partition//
- }//end of class//
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement