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

vector subscript out of range - bubble sort

本文关键字:范围 冒泡排序 下标      更新时间:2023-10-16

我有一段代码,它实现了数组的气泡排序。在MS VS 2012中编译,它在一定程度上起作用:

UPD:我添加了很多检查来追踪坠机发生的确切地点,就像这样:它交换一个数组的前两个元素,打印出一个交换了这些元素的数组,然后打印出"Checking"并用"vector subscript out 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 sizen");
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;
}

这一定是一件非常简单的事情,但我做不到。附言现在没有尴尬的_asm;-)

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

必须成为

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

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

您有一个"逐个关闭"错误:

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