Skip to content
This repository has been archived by the owner on Feb 21, 2021. It is now read-only.

Commit

Permalink
Quick sort in java. (#54)
Browse files Browse the repository at this point in the history
* Quick sort in java.

* fixes

* lint fixes
  • Loading branch information
hackbansu authored Oct 23, 2020
1 parent 87278e3 commit 2c3a084
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions Sorting/quick-sort/quickSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import java.io.*;
import java.util.*;

public class Quick_Sort {
public static void main(String[] args) {
int[] arr = takeinput();

// sort the array
Quick_Sort(arr, 0, arr.length - 1);

// display the array
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}

public static int[] takeinput() {
Scanner scn = new Scanner(System.in);

// input array length
int n = scn.nextInt();

int[] arr = new int[n];

for (int i = 0; i < arr.length; i++) {
// input array elements
arr[i] = scn.nextInt();
}

return arr;
}

public static void Quick_Sort(int[] arr, int lo, int hi) {
// if low index is higher than high index, simply return
if (lo >= hi)
return;

// define pivot
int pi = (lo + hi) / 2;
int pivot = arr[pi];
int left = lo, right = hi;

while (left <= right) {
while (arr[left] < pivot)
left++;

while (arr[right] > pivot)
right--;

if (left <= right) {
// swap the values
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}

Quick_Sort(arr, lo, right);
Quick_Sort(arr, left, hi);
}
}

0 comments on commit 2c3a084

Please sign in to comment.