Skip to content

Commit

Permalink
add QuickSort and TopK algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
Yingyi Zhang committed Sep 5, 2017
1 parent c87f5d6 commit bfdd222
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
10 changes: 10 additions & 0 deletions Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
public class Main{
public static void main(String[] args){
QuickSort lc = new QuickSort();
int[] nums = {4, 2, 3, 1,5, 7,6,6};
lc.quickSort(nums, 0, nums.length - 1);
for(int i = 0; i < nums.length; ++i){
System.out.println(nums[i]);
}
}
}
26 changes: 26 additions & 0 deletions QuickSort/QuickSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
public class QuickSort{
public void quickSort(int[] nums, int start, int end){
if(start >= end) return;
int pos = partition(nums, start, end);
quickSort(nums, start, pos - 1);
quickSort(nums, pos + 1, end);
}

public int partition(int[] nums, int start, int end){
int pivot = nums[end];
int pos = start - 1, tmp = 0;
for(int i = start; i < end; ++i){
if(nums[i] <= pivot){
++pos;
tmp = nums[pos]; // swap
nums[pos] = nums[i];
nums[i] = tmp;
}
}
// swap
nums[end] = nums[pos + 1];
nums[pos + 1] = pivot;

return pos + 1;
}
}
34 changes: 34 additions & 0 deletions QuickSort/TopK.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
public class TopK{
public void getTopK(int nums[], int k){
int start = 0, end = nums.length - 1;
int pos = partition(nums, start, end);
while(pos != k - 1){
if(pos > k - 1){
end = pos - 1;
}else{
start = pos + 1;
}
pos = partition(nums, start, end);
}
for(int i = 0; i < k; ++i)
System.out.println(nums[i]);
}

public int partition(int[] nums, int start, int end){
int pivot = nums[end];
int pos = start - 1, tmp = 0;
for(int i = start; i < end; ++i){
if(nums[i] <= pivot){
++pos;
//swap
tmp = nums[pos];
nums[pos] = nums[i];
nums[i] = tmp;
}
}
// swap
nums[end] = nums[pos + 1];
nums[pos + 1] = pivot;
return pos + 1;
}
}

0 comments on commit bfdd222

Please sign in to comment.