我有這段代碼實現了數組的氣泡排序。 被編譯在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現在;-)
if((int *)Array [i] == NULL)你這樣做?! – ForEveR
好吧,我懷疑如果它確實是== NULL,那麼有些地方是錯誤的。 – Chiffa
爲什麼爲空?爲什麼不'Array [i] == 0'? – ForEveR