向量下标超出范围 - 冒泡排序

时间:2012-08-30 20:53:24

标签: c++ vector sorting

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

UPD:我已经添加了很多检查来跟踪发生崩溃的确切位置,就像这样: 它交换数组的前两个元素,打印出一个交换了这些元素的数组,然后打印出“Checking”并崩溃,“vector subscript out of range”

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

2 个答案:

答案 0 :(得分:3)

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

必须成为

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

对于维数为N的索引,索引从0到N - 1

答案 1 :(得分:2)

你有一个“一个一个”的错误:

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]);