插入排序:
#include<iostream> using namespace std; int main() { int num[] = {23,12,54,3,26,88,21}; for(int j=1;j<7;j++) { int key = num[j]; int i=j-1; while(i>=0 && num[i]>key) { num[i+1] = num[i]; i--; } num[i+1] = key; } for(int i=0;i<7;i++) cout<<num[i]<<" "; return 0; }
选择排序:
#include<iostream> using namespace std; int main() { int num[] = {6,27,12,3,45,88,2,67,7}; for(int i=0;i<9;i++) { int min = num[i]; int index = i; for(int j=i+1;j<9;j++) { if(num[j] < min) { min = num[j]; index = j; } } num[index] = num[i]; num[i] = min; } for(int i=0;i<9;i++) cout<<num[i]<<" "; return 0; }