繁体   English   中英

为什么在这种情况下插入排序停止工作?

[英]Why does insertion sort stops working in this case?

在 function插入排序中,我定义了一个变量temp ,它等效于arr[i] 对于下面的while 循环,我写了一些条件,其中一个是temp < arr[j]) ,这段代码工作得很好。 但是,如果我在条件[ ie while(j >= 0 && arr[i] < arr[j]) ]中用arr[i]替换此temp ,则此代码确实按预期工作。 为什么会发生这种情况,变量temparr[i]的值不一样,正如它上面两行所定义的那样?

使用while(j >= 0 && arr[i] < arr[j]) ,它不起作用。
错误的

使用while(j >= 0 && temp < arr[j]) ,它可以工作。
正确的

#include<iostream>

void printSortedArray(int arr[], int size){
    std::cout<<"{ ";
    for(int m=0; m<size-1; ++m){
    std::cout<<arr[m]<<", ";
    }
    std::cout<<arr[size-1]<<" ";
    std::cout<<"}";
}

void insertionSort(int arr[], int size){
for(int i=1; i<size; ++i){
    int temp = arr[i];                     //  <---- Variable *temp* ----
    int j = i - 1;
    while(j >= 0 && temp < arr[j]){        //  <---- *while loop*----
        arr[j+1] = arr[j];
        --j;
    }
    arr[j+1] = temp;
}

printSortedArray(arr, size);
}

int main(){
int n; std::cout<<"Enter the size of array : ";
std::cin>>n;

int arr[n];

for(int i=0; i<n; ++i){
    std::cout<<"Enter the element at index ~ "<<i<<" : ";
    std::cin>>arr[i];
}

insertionSort(arr, n);
}

循环条件应该是while (j > 0 && temp < arr[j])和 end arr[j] = temp; 而不是arr[j+1] = temp;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM