c插入排序错误

时间:2011-11-08 03:52:30

标签: c insertion-sort

我正在进行c插入排序,它工作正常,但排序后第一个数字总是一个奇怪的负数,程序错误输出。

#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;
}

2 个答案:

答案 0 :(得分:3)

你将超过循环中的数组大小。当current = last时,list [last]是list [100],数组的第101个元素......这也不好。

编辑。我刚刚测试了它,它对我有用。我唯一改变的是外部循环中的&lt; = n&lt;

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

答案 1 :(得分:2)

如果声明一个类似

的数组
int numbers[100]

数字[99] 是最后一个元素。在排序功能中,您也可以访问数字[100]