冒泡排序
巨小数字
为什么会出现第一个数字呢?
我生成随机数的代码如下
发现元凶了!给SortedIndex赋的初值是N,那么比较的时候数组下标越界了!然后把原来的最后一位扔掉了TAT
SortedIndex 的无效优化
这里的SortedIndex始终让j的扫描范围为整个数列
改进后
C源码
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define N 10 //the size of the array
//bubble sort and its test program
void BubbleSort(int* array)
{
int isSorted = 1;//to decide wether the array is ordered
int SortedIndex = N - 1;//to record the left sorted index
int i,j;
int temp;
int thisIndex;
for(i = 0; i < N; i++)//control the loop times
{
isSorted = 1;//initialize the state
for(j = 0; j < SortedIndex; j++)//SortedIndex is the right boundary of sorted elements
//which can spare you of a lot trouble of sorting ordered array
{
if(array[j] > array[j + 1])
{
isSorted = 0;//the array is not in order yet
temp = array[j];//exchange the order
array[j] = array[j + 1];
array[j + 1] = temp;
thisIndex = j;
}
}
if(isSorted)
break; //if the array is already in order, then stop the loop
SortedIndex = thisIdex;//renew the right boundary of sorted elements
}
}
int main()
{
srand((unsigned int)time(0));//initialize the seed
int i;
int*array = (int*)malloc(sizeof(int)*N);
for(i = 0; i < N; i++)
{
array[i] = rand()%100 - 50;//to generate random number from -50 to 50
}
BubbleSort(array);
for(i = 0; i < N; i++)
{
printf("%d ",array[i]);
}
return 0;
}