使用c鱼丸进行编译,编译的一维数组的桶排序模板,函数不限
定,可以有多个参数。
#include <stdio.h>
#define MAX 10
// Function to sort an array using bucket sort
void bucketSort(int array[], int n)
{
int i, j;
int count[MAX]; // An array to store the count of each element in the input array.
// Initialize all elements of count[] as 0.
for (i = 0; i < MAX; i++) { //Loop through the count array and set each value to 0.
count[i] = 0; //Set the value at each index in the count array to 0.
}
// Store the count of each element in the input array
for (i = 0; i < n; i++) { //Loop through input array and increment corresponding index in count by 1.
++count[array[i]]; }
// Sort using insertion sort algorithm on a one-dimensional array
for (i = 1; i <= MAX - 1; i++) { //Loop through every element of one-dimensional sorted array starting from second element(index=1).
j = i - 1 ; //Store current element's index in j variable.
while (j >= 0 && count[j] > count[j + 1]) { //Check if current element is greater than previous, if yes then swap them.
int temp =count [j]; //Swap current and previous elements using temp variable as intermediate storage space.
count [j] =count [j + 1]; //Set current index's value with next index's value after swapping is done.
count [j + 1] =temp ; //Decrement j so that it now points to previous index, repeat loop until condition fails or j becomes negative(-1).
--j ; } } // Print sorted data printf("Sorted Data "); for (i=0 ; i<n ; ++i) { printf("%d ",count[i]); } } /* Driver program to test above function */ int main() { int arr[]= {4,2,9,6,23,12}; int n= sizeof(arr)/sizeof(arr[0]); bucketSort(arr ,n); return 0;}
创作工场
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。
点击这里>>使用🔥专业版,更聪明、更完整、更原创!