不稳定排序有 选择排序 快速排序
#include<iostream>
using namespace std;
#define swap(a,b){\
__typeof(a) _temp = a; a = b; b = _temp;\
}
//选择排序
void select_sort(int *num,int n){
for(int i = 0; i < n - 1; i++){
int ind = i;
for(int j = i + 1 ; j < n ; j++){
if(num[ind] > num[j]) ind =j;
}
swap(num[i] , num[ind]);
}
return;
}
//快速排序
void quick_sort(int *num, int l, int r){
if(r <= l){
return ;
}
int x = l, y = r, z = num [l];
while(x < y){
while(x < y && num[y] >= z) --y;
if(x < y) num[x++] = num[y];
while(x < y && num[x] <= z) ++x;
if(x < y) num[y--] = num[x];
}
num[x] = z;
quick_sort(num, l ,x - 1);
quick_sort(num, x + 1 , r);
}
java 实现
import java.util.Arrays;
public class Quicksort {
public static void main(String[] args) {
int[] a ={2,1,3,4,5,8,9};
quicksort(a,0,6);
System.out.println(Arrays.toString(a));
}
public static void quicksort(int[] num, int l ,int r){
if(r <= l){
return;
}
int x = l , y = r , z = num[l];
while(x < y){
while(x < y && num[y] > z ) y--;
if(x < y) num[x++] = num[y];
while(x < y && num[x] < z) x++;
if(x < y) num[y--] = num[x];
}
num[x] = z;
quicksort(num,l ,x - 1 );
quicksort(num, x + 1, r);
}
}
int main(){
int num[10]={2,3,1,4,7,5,6,8,9,0};
//select_sort(num, 10);
quick_sort(num,0,9);
for(int i = 0; i < 10; i++){
cout<<num[i]<<" ";
}
return 0;
}