Zac*_*ack 2 c++ algorithm insertion-sort
我对插入排序的实现似乎是在排序第一个元素的例外.我这里有一个小测试用例.谁能告诉我算法有什么问题?
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
void Insert(int *S, int k)
{
int key = S[k];
int j = k-1;
while(j>0 && S[j] > key)
{
S[j+1] = S[j];
j--;
}
S[j+1] = key;
}
void Insertionsort(int S[], int n)
{
if(n>1)
Insertionsort(S,n-1);
Insert(S,n);
}
int main()
{
srand ( time(NULL) );
int S1_8[8];
for(int i=0; i<8; i++)
S1_8[i] = rand()%100;
Insertionsort(S1_8,8);
for(int i=0; i<8; i++)
{
cout << S1_8[i] << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第一次Insert被调用,它被传递 int key = S[8];
S[8]不在数组范围内.
做那个
void Insertionsort(int S[], int n)
{
if(n>1)
Insertionsort(S,n-1);
Insert(S,n-1);
}
Run Code Online (Sandbox Code Playgroud)
此外,在你的条件下,它必须是
while(j>=0 && S[j] > key)
Run Code Online (Sandbox Code Playgroud)