Just-Zzz Sort


Quick Sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class  {
private int[] array;

public int[] sort(int[] input) {
if (input == null || input.length == 0)
return input;
this.array = input;
quicksort(array, 0, array.length - 1);
return array;
}

public void quicksort(int[] nums, int begin, int end) {
if (begin < end) {
int pos = partition(nums, begin, end);
quicksort(nums, begin, pos - 1);
quicksort(nums, pos + 1, end);
}
}

public int partition(int[] nums, int begin, int end) {
int pivot = nums[begin];
int l = begin + 1, r = end;
while (l <= r) {
if (nums[l] > pivot && nums[r] < pivot) {
swap(nums, l++, r--);
}
if (nums[l] <= pivot)
++l;
if (nums[r] >= pivot)
--r;
}

swap(nums, begin, r);
return r;
}

public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}

Merge Sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class MergeSort {
private int[] array;

public int[] sort(int[] input) {
this.array = input;
split(array, 0, array.length - 1);
return array;
}

public void split(int[] nums, int begin, int end) {
if (begin < end) {
int mid = begin + (end - begin) / 2;
split(nums, begin, mid);
split(nums, mid + 1, end);
merge(nums, begin, mid + 1, end);
}
}

public void merge(int[] nums, int begin, int mid, int end) {
int[] left = new int[mid - begin];
int[] right = new int[end - mid + 1];
for (int i = 0; i < left.length; ++i) {
left[i] = nums[begin + i];
}
for (int i = 0; i < right.length; ++i) {
right[i] = nums[mid + i];
}
int i = 0, j = 0, index = begin;
while (i < left.length && j < right.length) {
if (left[i] < right[j]) {
nums[index++] = left[i++];
} else {
nums[index++] = right[j++];
}
}
while (i < left.length) {
nums[index++] = left[i++];
}
while (j < right.length) {
nums[index++] = right[j++];
}
}
}