# 几种排序算法代码

163人阅读 评论(0)

## 选择排序

void select(int[] a) {
for(int i = 0; i < a.length;i ++) {
for(int j = i; j < a.length; j ++) {
int ai = a[i];
int aj = a[j];
if(a[i] > a[j]) {
a[i] = aj
a[j] = ai;
}
}
}


## 冒泡排序

void bubble(int[] a) {
BOOL exchanged = YES;
for (int i = 0; i < a.length - 1 && exchanged; i ++) {
exchanged = NO;
for (int j = 0; j < (a.length - 1 - i); j ++) {
int aj = a[j];
int aj1 = a[j + 1];
if (aj > aj1) {
exchanged = YES;
a[j + 1] = aj;
a[j] = aj1;
}
}
}
}


## 快速排序

void quick(int[] a, int left, int right){   if (left < right) {
int key = a[left];
int low = left;
int high = right;
while (low < high) {
while (low < high && a[high] >= key) {
high --;
}
a[low] = a[high];
while (low < high && a[low] <= key) {
low ++;
}
a[high] = a[low];
}
a[low] = key;
quick(a, left, low - 1);
quick(a, low + 1, right);
}
}


## 插入排序

void insert(int[] a) {
for (int i = 1; i < a.length; i ++) {
int ai = a[i], aj;
int j = i;
while (j > 0 && (aj = a[j - 1]) > ai) {
a[j] = aj;
j --;
}
a[j] = ai;
}
}


## 汉诺塔排序

void hanoi(int i , char A , char B , char C) {
if(i == 1) {
move(i , A , C);
} else {
hanoi(i - 1 , A , C , B);
move(i , A , C);
hanoi(i - 1 , B , A , C);
}
}

void move(int i , char x , char y) {
printf("Move disk i from x to y");
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：20463次
• 积分：541
• 等级：
• 排名：千里之外
• 原创：31篇
• 转载：11篇
• 译文：0篇
• 评论：5条
文章分类
阅读排行
最新评论