温馨提示×

c语言直接排序算法代码怎么写

小亿
79
2023-11-04 15:05:44
栏目: 编程语言

下面是一个使用C语言实现的直接排序算法的示例代码:

#include <stdio.h>

// 直接排序函数
void straightSort(int arr[], int n) {
    int i, j, minIndex, temp;
    
    // 遍历数组元素
    for (i = 0; i < n - 1; i++) {
        minIndex = i;
        
        // 找到最小值的索引
        for (j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        
        // 将最小值与当前元素交换位置
        temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    straightSort(arr, n);
    
    printf("排序后的数组:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}

这个代码示例中,straightSort函数接收一个整型数组和数组的长度作为参数,使用直接排序算法对数组进行排序。straightSort函数中的两个嵌套循环用于查找未排序部分中的最小值,并将其与当前元素交换位置,这样每次迭代时,未排序部分的最小值都会被移动到已排序部分的末尾。最终,数组中的元素将按升序排列。

main函数中,我们声明一个整型数组,并通过调用straightSort函数对其进行排序。然后,使用循环遍历并打印排序后的数组。输出结果为:11 12 22 25 34 64 90。

0