一、c語言一維數組排序從小到大
在c語言中,可以使用冒泡排序算法對一維數組進行排序,具體代碼如下:
#include <stdio.h> void bubbleSort(int arr[], int n) { int i, j, temp; for (i = 0; i < n - 1; i++) { for (j = 0; j arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } int main() { int arr[] = {5, 2, 8, 4, 1}; int n = sizeof(arr) / sizeof(arr[0]); bubbleSort(arr, n); printf("Sorted array: \n"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; }
上述代碼中通過兩層for循環遍曆數組,並通過if語句進行元素交換,實現了一維數組的排序。
二、c語言數組從小到大排序函數
c語言中提供了qsort函數,可以對數組進行快速排序,代碼如下:
#include <stdio.h> #include <stdlib.h> int compare(const void* a, const void* b) { return (*(int*)a - *(int*)b); } int main() { int arr[] = {5, 2, 8, 4, 1}; int n = sizeof(arr) / sizeof(arr[0]); qsort(arr, n, sizeof(int), compare); printf("Sorted array: \n"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; }
上述代碼中通過使用qsort函數,指定比較函數compare對數組進行排序,實現了更加高效的排序。
三、js數組從小到大排序sort方法
在javascript中,可以使用sort方法對數組進行排序,代碼如下:
var arr = [5, 2, 8, 4, 1]; arr.sort(function(a, b){return a - b}); console.log("Sorted array: " + arr);
上述代碼中通過sort方法,並傳遞一個函數作為參數來對數組進行排序,實現了js數組的排序。
四、一維數組從小到大排序
PHP中提供了sort函數,可以對一位數組進行排序,代碼如下:
上述代碼中使用sort函數對數組進行排序,並通過foreach循環遍曆數組輸出排序結果。
五、C語言數組從小到大排序
在c語言中,使用qsort函數可以對一維數組進行排序,代碼如下:
#include <stdio.h> #include <stdlib.h> int compare(const void * a, const void * b) { return (*(int*)a - *(int*)b); } int main() { int numbers[] = {5, 2, 8, 4, 1}; int n = sizeof(numbers) / sizeof(numbers[0]); qsort(numbers, n, sizeof(int), compare); for (int i=0; i<n; i++) { printf("%d ", numbers[i]); } return 0; }
上述代碼中通過使用qsort函數,並指定比較函數compare對數組進行排序並輸出結果。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/194222.html