理解:进行n轮循环,相邻元素两两比较,交换位置
先将最大/最小元素放到最后一个位置
然后缩小j的比较范围,因为每一轮循环最后一个元素的位置都已经确定了
#include
void bubble_sort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j+1]) { //决定是升序还是降序 “>”代表升序 “<”代表降序
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
和冒泡的区别:虽然都是一轮循环至少确定一个元素的正确位置,但是选择排序比较的对象很多,但是做的交换每轮只做一次
而冒泡排序每个循环都做多个的元素交换
#include
void selection_sort(int arr[], int n) {
int i, j, minIndex;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11,43,54};
int n = sizeof(arr) / sizeof(arr[0]);
selection_sort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
每轮依次增加元素进行比较,然后将新添加的元素添加到正确的位置
重要的是对之前数组的比较
#include
void insertionSort(int arr[],int n) {
int preIndex, current;
for (int i = 1; i < n; i++) {
preIndex = i - 1;
current = arr[i];
while(preIndex >= 0 && arr[preIndex] > current) {
arr[preIndex+1] = arr[preIndex];
preIndex--;
}
arr[preIndex+1] = current;
}
}
int main() {
int arr[] = {10,8,11,7,4,12,9,6,5,3};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
分块进行排序
#include
void quickSort(int arr[], int start, int end) {
if (start >= end) {
return;
}
int left = start, right = end;
int pivot = arr[start];
while (left <= right) {
while (arr[left] < pivot) {
left++;
}
while (arr[right] > pivot) {
right--;
}
if (left <= right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
quickSort(arr, start, right);
quickSort(arr, left, end);
}
int main() {
int arr[] = {10, 8, 11, 7, 4, 12, 9, 6, 5, 3};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}