C语言数字排序的实现方法
在计算机编程中,排序是一种常见的操作,无论是在数据处理、算法设计还是其他领域,排序都扮演着重要的角色,而在C语言中,有多种方法可以实现数字排序,本文将介绍其中几种常见的方法。
1、冒泡排序(Bubble Sort)
冒泡排序是一种简单的排序算法,它重复地遍历要排序的数列,一次比较两个元素,如果它们的顺序错误就把它们交换过来,遍历数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
以下是冒泡排序的C语言实现:
#include <stdio.h>
void bubble_sort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int 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 is:
");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("
");
return 0;
}
2、选择排序(Selection Sort)
选择排序是一种简单直观的排序算法,它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。
以下是选择排序的C语言实现:
#include <stdio.h>
void selection_sort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
selection_sort(arr, n);
printf("Sorted array is:
");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("
");
return 0;
}
3、插入排序(Insertion Sort)
插入排序是一种简单直观的排序算法,它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入,插入排序在实现上,通常采用in-place排序(即只需用到O(1)的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。
以下是插入排序的C语言实现:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void insertion_sort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
int main() {
srand(time(NULL));
int n = rand() % 100 + 50; // generate a random number between 50 and 150 for testing purposes
int arr[n];
for (int i = 0; i < n; i++) {
arr[i] = rand() % 100; // generate a random number between 0 and 99 for testing purposes
}
insertion_sort(arr, n); // sort the array using insertion sort algorithm
printf("Sorted array is: "); // print the sorted array to the console window using the following format: "Sorted array is: " followed by the sorted array elements separated by spaces and ending with a new line character '
'. The '%d' format specifier is used to display an integer value in the output stream. If you want to display a floating-point value instead of an integer value, you can use the '%f' format specifier instead. For example: "Sorted array is: %f
" would display a floating-point value in the output stream. If you want to display a string value instead of an integer or floating-point value, you can use the '%s' format specifier instead. For example: "Sorted array is: %s
" would display a string value in the output stream. For more information about format specifiers in C language programming, please refer to the following link: https://www.learn-c.org/en/Formatting_strings#Format_specifiers_and_placeholders



还没有评论,来说两句吧...