1、简单的冒泡排序算法
int array[] = {3, 5, 1, 6, 8, 2, 4, 9, 7};
int count = sizeof(array) / sizeof(array[0]);
int flag = 0;
for (int i = 0; i < count - 1 && flag == 0; i++) {
flag = 1;
for (int j = 0; j < count - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = 0;
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
flag = 0;
}
}
}
for (int i = 0; i < count; i++) {
printf("[%2d] = %d\n", i, array[i]);
}
int count = sizeof(array) / sizeof(array[0]);
int flag = 0;
for (int i = 0; i < count - 1 && flag == 0; i++) {
flag = 1;
for (int j = 0; j < count - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = 0;
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
flag = 0;
}
}
}
for (int i = 0; i < count; i++) {
printf("[%2d] = %d\n", i, array[i]);
}
2、选择排序算法
for(int i = 0; i < count - 1; i++){
int minIndex= i;
for (int j = minIndex + 1; j < count; j++) {
if (array[minIndex] > array[j]) {
minIndex = j;
}
}
if(minIndex != i){
int temp = 0;
temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}
for (int i = 0; i < count; i++) {
printf("[%2d] = %d\n", i, array[i]);
}
int minIndex= i;
for (int j = minIndex + 1; j < count; j++) {
if (array[minIndex] > array[j]) {
minIndex = j;
}
}
if(minIndex != i){
int temp = 0;
temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}
for (int i = 0; i < count; i++) {
printf("[%2d] = %d\n", i, array[i]);
}
3、插入排序
int array[] = {3, 5, 1, 6, 8, 2, 4, 9, 7};
int count = sizeof(array) / sizeof(array[0]);
int temp = 0;
int j = 0;
for (int i = 1; i < count; i++) {
j = i;
temp = array[j];
while (j > 0 && temp < array[j - 1]) {
array[j] = array[j - 1];
j--;
}
array[j] = temp;
}
for(int i = 0; i < count; i++){
printf("[%2d] = %d\n", i, array[i]);
}
int count = sizeof(array) / sizeof(array[0]);
int temp = 0;
int j = 0;
for (int i = 1; i < count; i++) {
j = i;
temp = array[j];
while (j > 0 && temp < array[j - 1]) {
array[j] = array[j - 1];
j--;
}
array[j] = temp;
}
for(int i = 0; i < count; i++){
printf("[%2d] = %d\n", i, array[i]);
}
4、快速排序算法
void quickSort(int array[], int count)
{
if (count < 2) { //出口.递归的上面
return;
}
int start = 0, end = count - 1;
int temp = array[start];
while (start < end) {
while (start < end && array[end] > temp) {
end--;
}
if (start < end) {
array[start] = array[end];
start++;
}
while (start < end && array[start] < temp) {
start++;
}
if (start < end) {
array[end] = array[start];
end--;
}
}
array[start] = temp;
quickSort(array, start);
quickSort(array + start + 1, count - start - 1);
}
{
if (count < 2) { //出口.递归的上面
return;
}
int start = 0, end = count - 1;
int temp = array[start];
while (start < end) {
while (start < end && array[end] > temp) {
end--;
}
if (start < end) {
array[start] = array[end];
start++;
}
while (start < end && array[start] < temp) {
start++;
}
if (start < end) {
array[end] = array[start];
end--;
}
}
array[start] = temp;
quickSort(array, start);
quickSort(array + start + 1, count - start - 1);
}