快速排序的实现
package algorithm
;
import java
.util
.Arrays
;
public class QuicklySort {
public static void main(String
[] args
) {
int[] arr1
= { 45, 28, 80, 90, 50, 16, 100, 10 };
quicklySort(arr1
, 0, arr1
.length
- 1);
echoArr(arr1
);
int[] arr2
= { 45, 28, 80, 90, 50, 16, 100, 10 };
codeSort(arr2
, 0, arr2
.length
- 1);
echoArr(arr2
);
}
public static void quicklySort(int[] arr
, int left
, int right
) {
int base
= arr
[left
];
int pointLeft
= left
;
int pointRight
= right
;
while (pointLeft
< pointRight
) {
while (pointLeft
< pointRight
&& arr
[pointRight
] >= base
) {
pointRight
--;
}
if(pointLeft
< pointRight
) {
int temp
= arr
[pointRight
];
arr
[pointRight
] = arr
[pointLeft
];
arr
[pointLeft
] = temp
;
pointLeft
++;
}
while (pointLeft
< pointRight
&& arr
[pointLeft
] <= base
) {
pointLeft
++;
}
if(pointLeft
< pointRight
) {
int temp
= arr
[pointRight
];
arr
[pointRight
] = arr
[pointLeft
];
arr
[pointLeft
] = temp
;
pointRight
--;
}
}
if(left
< pointLeft
) {
quicklySort(arr
, left
, pointLeft
- 1);
}
if(pointLeft
< right
) {
quicklySort(arr
, pointLeft
+ 1, right
);
}
}
public static void codeSort(int[] arr
, int left
, int right
) {
int base
= arr
[left
];
int pointLeft
= left
;
int pointRight
= right
;
while (pointLeft
< pointRight
) {
while (pointLeft
< pointRight
&& arr
[pointRight
] >= base
) {
pointRight
--;
}
if(pointLeft
< pointRight
) {
int temp
= arr
[pointRight
];
arr
[pointRight
] = arr
[pointLeft
];
arr
[pointLeft
] = temp
;
pointLeft
++;
}
while (pointLeft
< pointRight
&& arr
[pointLeft
] <= base
) {
pointLeft
++;
}
if(pointLeft
< pointRight
) {
int temp
= arr
[pointRight
];
arr
[pointRight
] = arr
[pointLeft
];
arr
[pointLeft
] = temp
;
pointRight
--;
}
}
if(left
< pointLeft
) {
codeSort(arr
, left
, pointLeft
- 1);
}
if(pointLeft
< right
) {
codeSort(arr
, pointLeft
+ 1, right
);
}
}
public static void echoArr(int[] arr
) {
for (int i
= 0; i
< arr
.length
; i
++) {
System
.out
.print(arr
[i
]+ " ");
}
System
.out
.println();
}
}
附本机执行结果如下:
10 16 28 45 50 80 90 100 10 16 28 45 50 80 90 100
转载请注明原文地址:https://ipadbbs.8miu.com/read-62330.html