【问题标题】:Array sorting in c by referencec中的数组按引用排序
【发布时间】:2021-06-15 08:25:05
【问题描述】:

我必须编写一个函数来在 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 循环的最后一次迭代中,array[i+1] 在数组之外。

标签: arrays c pointers pass-by-reference bubble-sort


【解决方案1】:

你正在离开数组的末尾:

    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++){

【讨论】:

  • 我现在很尴尬;谢谢,7 分钟内接受答复
【解决方案2】:

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]); 
           }
       }
    }
} 

【讨论】:

    猜你喜欢
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 2012-11-07
    • 2015-05-13
    相关资源
    最近更新 更多