1.选择排序
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void select_sort(int nums[], int len) {
int temp;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (nums[j] < nums[i]) {
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
}
int main(int arg, int* argv) {
int nums[10] = { 30, 10, 3, 5, 58, 43, 50, 27, 11, 19 };
select_sort(nums, 10);
for (int i = 0; i < 10; i++) {
printf("%d ", nums[i]);
}
printf("\n");
getchar();
}
2.冒泡排序
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void bubble_sort(int nums[], int len) {
int temp;
bool status = true;
for (int i = 0; i < len && status; i++) {
status = false;
for (int j = len - 1; j > i; j--) {
if (nums[j-1] > nums[j]) {
temp = nums[j-1];
nums[j-1] = nums[j];
nums[j] = temp;
status = true;
}
}
}
}
int main(int arg, int* argv) {
int nums[10] = { 30, 10, 3, 5, 58, 43, 50, 27, 11, 19 };
bubble_sort(nums, 10);
for (int i = 0; i < 10; i++) {
printf("%d ", nums[i]);
}
printf("\n");
getchar();
}
3.快速排序
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void quick_sort(int* nums, int low, int high) {
if (low >= high) {
return;
}
int base;
base = *(nums + low);
int left = low;
int right = high;
while (left != right)
{
while (left < right && (*(nums + right) > base))
{
right--;
}
if (left < right) {
*(nums + left) = *(nums + right);
left++;
}
while (left < right && (*(nums + left) <= base))
{
left++;
}
if (left < right) {
*(nums + right) = *(nums + left);
right--;
}
}
*(nums + left) = base;
quick_sort(nums, low, left - 1);
quick_sort(nums, left + 1, high);
}
int main(int arg, int* argv) {
int nums[10] = { 30, 10, 3, 5, 58, 43, 50, 27, 11, 19 };
quick_sort(nums, 0, 9);
for (int i = 0; i < 10; i++) {
printf("%d ", nums[i]);
}
printf("\n");
getchar();
}
|