冒泡排序:
int[] a = {345,7,32,5,4,7};
for (int i = 0; i < a.length-1; i++) {
for (int j = i+1; j < a.length; j++) {
if (a[i]>a[j]){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
快速排序(无重复值):
public class SortTest {
public static void main(String[] args) {
int[] a = {345,7,32,5,4,3,12,23,110};
show(a);
quickSort(a,0,a.length-1);
show(a);
}
private static void quickSort(int[] a, int start, int end) {
if (start>=end)
return;
int i=start;
int j=end;
int index = start;
while(i<j){
while(a[j]>a[index]){
j--;
}
index = swap(a,j,index);
while(a[index]>a[i]){
i++;
}
index = swap(a,i,index);
}
quickSort(a, start, index-1);
quickSort(a, index+1, end);
}
private static int swap(int[] a, int n, int index) {
int tmp = a[n];
a[n] = a[index];
a[index] = tmp;
return n;
}
private static void show(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]);
if (i!=a.length-1){
System.out.print("\t");
}else{
System.out.println();
}
}
}
}
快速排序(可含重复值)
public class SortTest {
public static void main(String[] args) {
int[] a = {345,7,32,5,4,-1,3,12,23,110,45645,321,456,78,-1,78,78,32,345};
show(a);
quickSort2(a,0,a.length-1);
show(a);
}
private static void quickSort2(int[] a, int start, int end) {
if (start>=end)
return;
int i=start;
int j=end;
int index = end;
while(i<j){
while(a[j]>a[index]){
j--;
}
if (j!=index && a[j]==a[index]){
index = swap(a,--j,index);
}else{
index = swap(a,j,index);
}
while(a[index]>a[i]){
i++;
}
if (i!=index && a[i]==a[index]){
index = swap(a,++i,index);
}else{
index = swap(a,i,index);
}
}
quickSort2(a, start, index-1);
quickSort2(a, index+1, end);
}
private static int swap(int[] a, int n, int index) {
int tmp = a[n];
a[n] = a[index];
a[index] = tmp;
return n;
}
private static void show(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]);
if (i!=a.length-1){
System.out.print("\t");
}else{
System.out.println();
}
}
}
}