溫馨提示×

c語言直接排序算法代碼怎么寫

小億
89
2023-11-04 15:05:44
欄目: 編程語言

下面是一個(gè)使用C語言實(shí)現(xiàn)的直接排序算法的示例代碼:

#include <stdio.h>

// 直接排序函數(shù)
void straightSort(int arr[], int n) {
    int i, j, minIndex, temp;
    
    // 遍歷數(shù)組元素
    for (i = 0; i < n - 1; i++) {
        minIndex = i;
        
        // 找到最小值的索引
        for (j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        
        // 將最小值與當(dāng)前元素交換位置
        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("排序后的數(shù)組:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}

這個(gè)代碼示例中,straightSort函數(shù)接收一個(gè)整型數(shù)組和數(shù)組的長度作為參數(shù),使用直接排序算法對數(shù)組進(jìn)行排序。straightSort函數(shù)中的兩個(gè)嵌套循環(huán)用于查找未排序部分中的最小值,并將其與當(dāng)前元素交換位置,這樣每次迭代時(shí),未排序部分的最小值都會(huì)被移動(dòng)到已排序部分的末尾。最終,數(shù)組中的元素將按升序排列。

main函數(shù)中,我們聲明一個(gè)整型數(shù)組,并通過調(diào)用straightSort函數(shù)對其進(jìn)行排序。然后,使用循環(huán)遍歷并打印排序后的數(shù)組。輸出結(jié)果為:11 12 22 25 34 64 90。

0