Pra*_*dav 0 c++ argument-passing insertion-sort
我正在尝试实现插入排序.当我在while循环中编写swap方法时,该算法工作正常.但是当我尝试调用swap()函数时,它给出了错误的答案.具体来说,当我传递参数'j'时,它会使答案出错.你能告诉我我犯了哪个错误.(关于ideone![ http://ideone.com/MoqHgn])
#include <iostream>
using namespace std;
void swap(int *x, int *y, int *j) {
int temp = *x;
*x = *y;
*y = temp;
*j--;
}
int main() {
int N;
scanf("%d", &N);
int a[N];
for(int i = 0; i < N; i++) {
scanf("%d", &a[i]);
}
for(int i = 1; i < N; i++) {
int j = i;
while(j > 0 && a[j-1] > a[j]) {
swap(&a[j-1], &a[j], &j);
//int temp = a[j];
//a[j] = a[j-1];
//a[j-1] = temp;
//j--;
}
}
for(int i = 0; i<N; i++) {
cout << a[i] << " ";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |