Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2020
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class QuickSort {
  4.     public static void main(String args[]) {
  5.         int[] arr = {25,23,141,241,512,321,521,12,312,4,125,1515};
  6.        
  7.         quickSort(arr, 0, arr.length - 1);
  8.         System.out.println(Arrays.toString(arr));
  9.     }
  10.     // This method sorts the array using quick sort algorithm
  11.     // It works in the following way
  12.     // 1- Partition the array:
  13.     //      1. Pick an element in the current array and call it pivot.
  14.     //      2. Put all the elements smaller than pivot before it, and all elements
  15.     //          greater than pivot after it.
  16.     //      3. By doing so, we can now know the correct index of pivot in the final sorted array
  17.     //          and return it
  18.     // 2- Now that we have the partition index (pivotIdx), repeat step 1 for the
  19.     //      following 2 sub-arrays: low -> pivotIdx - 1, and pivotIdx + 1 -> high
  20.     public static void quickSort(int[] arr, int low, int high){
  21.         if(low < high){
  22.             int pivotIdx = partition(arr, low, high);
  23.             quickSort(arr, low, pivotIdx - 1);
  24.             quickSort(arr, pivotIdx + 1, high);
  25.         }
  26.     }
  27.    
  28.     public static int partition(int[] arr, int low, int high){
  29.         int pivot = arr[high];
  30.         int i = low - 1;
  31.        
  32.         for(int j = low; j < high; j++){
  33.             if(arr[j] <= pivot){
  34.                 i++;
  35.                 swap(arr, i, j);
  36.             }
  37.         }
  38.         // Correct position of pivot is i + 1 because we placed the smaller elements
  39.         // starting from low -> i
  40.         swap(arr, i + 1, high);
  41.        
  42.         return i + 1;
  43.     }
  44.    
  45.     // Methods that swaps two elements of an array
  46.     public static void swap(int[] arr, int i, int j){
  47.         int temp = arr[i];
  48.         arr[i] = arr[j];
  49.         arr[j] = temp;
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement