c中的数组按引用排序

Array sorting in c by reference

我必须编写一个函数来对 C 中的整数数组进行排序:

代码:

// the function:

void my_sort_intarr(int *array, int size){
    int tmp;
    int sorted = 1;
    while(sorted == 1){
        sorted = 0;
        for (int i = 0 ; i < size ; i++){
            if(array[i] > array[i+1]){
                tmp = array[i];
                array[i] = array[i+1];
                array[i+1] = tmp;
                sorted = 1;
            }
            if (array[i] == array[i+1]){
                continue;
            }
        }
    }
}

// My Main
void my_sort_intarr(int *array, int size);

int main(){
    int arr[7] = {9, 4, 8, 2, 3, 3, 9};
    my_sort_intarr( arr, 7);
    for (int i = 0; i < 7; i++){
        printf("%d\n", arr[i]);
    }
    return 0;
}

测试时我得到了结果: 0 2 3 3 4 8 9 我想知道 0 来自哪里以及如何正确执行此操作。

您将离开数组的末尾:

    for (int i = 0 ; i < size ; i++){
        if(array[i] > array[i+1]){

isize-1 时,array[i+1] 是数组末尾后的一个元素。超出数组边界的读取或写入会触发 undefined behavior,在本例中表现为 0 元素出现在列表中。

将循环条件更改为:

    for (int i = 0 ; i < size - 1 ; i++){

OP 发布的代码不是有效的排序算法。 IE。结果不会总是对 int 元素的列表进行排序,尤其是当一个小元素接近列表末尾时。

sorting algorithms

建议(简单但随着元素数量的增加而变慢) Bubble Sort

冒泡排序算法:

void swap(int *xp, int *yp) 
{ 
    int temp = *xp; 
    *xp = *yp; 
    *yp = temp; 
} 

// A function to implement bubble sort 
void bubbleSort(int arr[], int n) 
{ 
   for ( int i = 0; i < n-1; i++) 
   {      
       // Last i elements are already in place    
       for ( int j = 0; j < n-i-1; j++) 
       { 
           if (arr[j] > arr[j+1]) 
           {
               swap(&arr[j], &arr[j+1]); 
           }
       }
    }
}