排序算法
总纲
归并排序
public MagazineNode sort(MagazineNode list) {
if (list == null || list.next == null) return list;
MagazineNode fast = list.next;
MagazineNode slow = list;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
MagazineNode tmp = slow.next;
slow.next = null;
MagazineNode left = sort(list);
MagazineNode right = sort(tmp);
MagazineNode h = new MagazineNode();
MagazineNode res = h;
while (left != null && right != null) {
if (left.magazine.toString().compareTo(right.magazine.toString()) < 0){
h.next = left;
left = left.next;
}else{
h.next = right;
right = right.next;
}
h = h.next;
}
h.next = left != null ? left : right;
return res.next;
}
快速排序
package DuiXiang;
public class Demo7 {
public static void main(String[] args) {
int arr[] = {123,124,43,645,746,823,537,135};
Quick(arr,0, arr.length - 1);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i] + " ");
}
}
public static void Quick(int arr[],int x,int y){
int start = x;
int end = y;
if(start > end){
return;
}
int baseNumber = arr[x];
while(start != end){
while(true){
if(end <= start || arr[end]< baseNumber){
break;
}
end--;
}
while(true){
if(end <= start || arr[start] > baseNumber){
break;
}
start++;
}
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
int temp2 = arr[end];
arr[end] = arr[x];
arr[x] = temp2;
Quick(arr,x,start - 1);
Quick(arr,start + 1,y);
}
}
插入排序
package DuiXiang;
public class Demo7 {
public static void main(String[] args) {
int arr[] = {123,5,124,426,14,126,125,14,124135};
int startIndex = 0;
for (int i = 0; i < arr.length - 1; i++) {
if(arr[i] > arr[i+1]){
startIndex = i + 1;
break;
}
}
for (int i = startIndex; i < arr.length; i++) {
int j = i;
while(j > 0){
if(arr[j] < arr[j - 1]){
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}else{
break;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
}