Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.array;
- import java.util.Arrays;
- import java.util.Scanner;
- import static com.array.quicksortmethods.quickSort;
- public class quicksortmain {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.println("Input the number of elements /N/ :");
- int N = input.nextInt();
- int[] arr = new int[N];
- for (int i = 0; i < N; i++) {
- System.out.printf("Input element [%d] : ", i);
- arr[i] = input.nextInt();
- }
- System.out.println("Before sorting : " + Arrays.toString(arr));
- quickSort(arr,0,N - 1);
- System.out.println("After sorting : " + Arrays.toString(arr));
- }
- }
- package com.array;
- public class quicksortmethods {
- 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);
- }
- }
- 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;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement