简体   繁体   English

C-插入排序算法

[英]C - Insertion Sort Algorithm

I'm trying to sort a set of numbers like this: 我正在尝试对一组数字进行排序,如下所示:

A[]={3,6,7,2,9,1,2,7,2}
A[]={3,6,7,2,2,2,9,1,7}

So I've made this: 所以我做了这个:

void sort_min(int* point, int size_array, int min_n){
    int i = 0;
    int j = 0;
    int k = 0;
    while(point[i] != min_n){
        i++;
    }
    j = i+1;
    while(point[j] != min_n){
        j++;
    }
    k = j;
    for (j-1; j > i; j--){
        point[j] = point[j-1];
    }
    point[j] = min_n;
    j = k+1;
}

Like you can notice I've never used the int size_array cause I don't know the way to match an iterative function like a for or a while (That's the question. How to solve it?). 就像您可以注意到的那样,我从未使用过int size_array因为我不知道匹配 for while 类的迭代函数的方式 (这是问题所在。如何解决?)。 I've done that, of course, but I've got a Segmentation fault like an answer. 当然,我已经做到了,但是我遇到了Segmentation fault例如答案。

The main concept is looking for a number int min_n and up to that point sort that number at each occurrence in the array. 主要概念是寻找一个整数int min_n ,直到该点在数组中每次出现时对该数字进行排序。

Thanks for all. 谢谢大家

You need use size_array like below, if you are asking about this. 如果您对此有size_array ,则需要使用如下所示的size_array

  1. You need compare i and j with size_array in while . 您需要在while size_array ijsize_array进行比较。

     while (i < size_array && point[i] != min_n) { i++ } 
  2. Need check value of i , j after while . while需要ij校验值。 They may be larger or equal to size_array. 它们可能大于或等于size_array。

     while (i < size_array && point[i] != min_n) { i++ } // I guess when you don't find min_n, function can just return. if (i >= size_array) return; j = i+1; while(j < size_array && point[j] != min_n){ // Also need check j's value. j++; } // Also guess when can't find the second min_n position, function can return. if (j >= size_array) return; k = j for (; j > i; j--) // No need j-1. point[j] = point[j-1]; // This is useless. When code come here, j == i and point[i] == min_n; point[j] = min_n; j = k+1; 

Try the Insertion Sort with the code as follows.. 尝试使用以下代码插入排序。

void sort_min(int point[], int size_array) 
{ 
   int i, key, j; 
   for (i = 1; i < size_array; i++) 
   { 
       key = point[i]; 
       j = i-1; 

       /* Move elements of arr[0..i-1], that are 
          greater than key, to one position ahead 
          of their current position */
       while (j >= 0 && point[j] > key) 
       { 
           point[j+1] = point[j]; 
           j = j-1; 
       } 
       point[j+1] = key; 
   } 
} 

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

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