且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

错误使用C插入排序

更新时间:2023-11-23 15:43:28

您去那边循环内的数组的大小。当电流=最后名单[最后]是列表[100],数组的第101元......这也是不好的。

编辑。我只是测试了这一点,它为我工作。我唯一​​改变是在< =在外环到n<

 无效插入排序(INT名单[],INT去年){
 INT保持;
 INT学步车;
 INT电流;
 诠释计数; 计数= 0;
 对于(电流= 1;电流I最后,目前++){
     举办​​=列表[现行];
     为(步行者=电流 - 1;
         沃克> = 0&放大器;&放大器;定妆LT;列表[步行者]沃克 - ){
                列表[步行者+ 1] =列表[步行者]
         }
     列表[步行者+ 1] =保持;
     算上++;
 }
 的printf(\\ n \\ NHOW多次通过排序\\ n%d个\\ n \\ n吗?,计数);
 返回;
}

I am making a c insertion sort and it works fine except that after the sort the first number is always a weird negative number and the program errors out.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void insertionSort(int list[], int last){
     int hold;
     int walker;
     int current;
     int count;

     count = 0;
     for (current = 1; current <= last; current++){
         hold = list[current];
         for (walker = current - 1; 
             walker >= 0 && hold < list[walker]; walker--){
                    list[walker + 1] = list[walker];
             }
         list [walker + 1] = hold;
         count++;
     }
     printf("\n\nHow many passes to sort?\n%d\n\n", count);
     return;
}

int main(int argc, char *argv[])
{
  int numbers[100];
  int i;

  srand(time(NULL));
  for (i = 0; i < 100; i++){
      numbers[i] = rand() % 100;
  }
  printf("Unsorted Numbers\n-------- -------\n");
  for (i = 0; i < 100; i++){
      printf("%d,", numbers[i]);
  }
  insertionSort(numbers, 100);
  printf("\nSorted Numbers\n-------- -------\n");
  for (i = 0; i < 100; i++){
      printf("%d,", numbers[i]);
  }
  system("PAUSE");  
  return 0;
}

You are going OVER the array size within the loop. When current = last, list[last] is list[100], the 101th element of the array... this is also not good.

Edit. I just tested this out and it worked for me. Only thing i changed was the <= in the outer loop to n <

void insertionSort(int list[], int last){
 int hold;
 int walker;
 int current;
 int count;

 count = 0;
 for (current = 1; current < last; current++){
     hold = list[current];
     for (walker = current - 1; 
         walker >= 0 && hold < list[walker]; walker--){
                list[walker + 1] = list[walker];
         }
     list [walker + 1] = hold;
     count++;
 }
 printf("\n\nHow many passes to sort?\n%d\n\n", count);
 return;
}