0

我有这段代码实现了数组的冒泡排序。在 MS VS 2012 中编译它可以工作到一定程度:

UPD:我添加了很多检查来跟踪发生崩溃的确切位置,就像这样:它交换数组的前两个元素,打印出交换了这些元素的数组,然后打印出“正在检查”并因“向量下标超出范围”而崩溃

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;


int Check(vector<int> Array)
{
printf ("Checking: \n");
for (int i = 0; i < Array.size(); i++)
    if((int*) Array[i] == NULL)
    {
        cerr << "Array [" << i << "] is fubared";
        return -1;
    }
}

int PrintOut(vector<int> Array)
{
printf ("Your array appears to be as follows: \n");
for (int i = 0; i < Array.size(); i++)
    printf("%d  ", Array[i]);
return 0;
}

int bubble_sort()
{
int or_size = 2;
int i, j, size, temp;

printf("Specify array size\n");
scanf_s("%d", &size);
printf(" Now, input all elements of the array \n");

vector<int> Array(size, 0);
if (size > or_size)
    Array.resize(size);

for (i = 0; i < size; i++)
{
    printf("Array [%d] is now re-initialised as ", i);
    scanf_s("%d", &temp);
    printf("\n");
    Array[i] = temp;
}

Check(Array);

PrintOut(Array);

for (i = 1; i < size; i++)
    for (j = 0; j < size-i ; j--)
    {
        printf ("Attempting to swap Array[%d], which = %d, and Array [%d], which = %d \n",j, Array[j], j+1, Array[j+1]);
        if (Array[j] > Array[j+1])
        {
            Array[j]+=Array[j+1];
            Array[j+1] = Array[j] - Array[j+1];
            Array[j] = Array[j] - Array[j+1];
            printf("Swapped \n");
        }
        PrintOut(Array);
        Check(Array);
    }

printf ("\n Your Array has been bubble_sorted and should know look like this: \n");
for (i = 0; i < size; i++)
    printf("%d ", Array[i]);

Array.clear();

return 0;
}

int main()
{
    bubble_sort();
    return 0;
}

它一定很简单,但我无法触及。PS现在没有尴尬的_asm ;-)

4

2 回答 2

3
for (j = size; i > 0; i--)

必须成为

for (j = size - 1; i > 0; i--)

对于维度为 N 的数组,索引从 0 变为 N - 1

于 2012-08-30T20:58:15.430 回答
2

你有一个“off-by-one”错误:

for (i = 0; i < size; i++)
    for (j = size; i > 0; i--)
    //   ^^^^
    //   j is out or range, the last valid index is size-1
        if (Array[j] < Array[j-1])
            swap(Array[j], Array[j-1]);
于 2012-08-30T20:59:03.277 回答