- Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathsort.java
More file actions
Latest commit
69 lines (57 loc) · 1.87 KB
/
Copy pathsort.java
File metadata and controls
69 lines (57 loc) · 1.87 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
importjava.util.*;
/*
* created by sijunhe on 05/09/2015
* Sorting - Implement two types of sorting algorithms: Merge sort and bubble sort
*/
publicclasssort {
publicstaticvoidmain(String[] args) {
int[] a = {15,8,7,3,9,2,1,6,8,12,5,8,6,22,31,1,0,3};
int[] b = {15,8,7,3,9,2,1,6,8,12,5,8,6,22,31,1,0,3};
mergeSort(a);
bubbleSort(b);
System.out.println("Test merge sort " + Arrays.toString(a));
System.out.println("Test bubble sort " + Arrays.toString(b));
}
publicstaticvoidmergeSort(int[] input){
int[] buff = newint[input.length];
mergeSort(input,buff,0,input.length-1);
}
privatestaticvoidmergeSort(int[] input, int[] buff, intlow, inthigh){
if (low<high){
intmid = (low+high)/2;
mergeSort(input,buff,low,mid);
mergeSort(input,buff,mid+1,high);
merge(input,buff,low,mid+1,high);
}
}
privatestaticvoidmerge(int[ ] input, int[ ] buff, intleft, intright, intrightEnd){
intleftEnd = right - 1;
intk = left;
intnum = rightEnd - left + 1;
while(left <= leftEnd && right <= rightEnd)
if(input[left] < input[right])
buff[k++] = input[left++];
else
buff[k++] = input[right++];
while(left <= leftEnd) //right array runs out, copy the rest of left array
buff[k++] = input[left++];
while(right <= rightEnd) //left array runs out, copy the rest of right array
buff[k++] = input[right++];
// Copy the sorted array from buffer back to the input array
for(inti = 0; i < num; i++, rightEnd--)
input[rightEnd] = buff[rightEnd];
}
publicstaticvoidbubbleSort(int[] original){
inttemp; //used for swapping elements
intn = original.length;
for (inti = 0; i < n - 1; i++){
for (intj = 0; j < n -1; j++){
if (original[j] > original[j + 1]){ //if earlier element is greater, swap
temp = original[j];
original[j] = original[j + 1];
original[j + 1] = temp;
}
}
}
}
}