I’m learning to deal with data structures and I’ve just written a program which Insertion_Sorts an array of integers.
The Sorting works perfectly well, so there;s no need to tackle it.
But I wish to give my user a way to search for a specific number in a Sorted array.
and it doesn’t work: more specifically:
i’ve compiled the following code in MS VS 2010 under Win7 x64 Ultimate, and after writing “Specify number to be searched” it crashes, and the debugger says “Access violation”.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <vector>
using namespace std;
int swap(int x, int y)
{
if(x != y)
{
_asm
{
mov eax,x;
mov ebx, y;
mov y,eax;
mov x, ebx;
}
}
return 0;
}
int insertion_sort()
{
int or_size = 2;
int i,j,k,h, size, temp;
char answ;
int xx;
char query [20];
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 (int i = 0; i < size; i++)
{
scanf_s("%d\n", &temp);
Array[i] = temp;
}
printf ("Your array appears to be as follows: \n");
for (int i = 0; i < size; i++)
printf("%d ", Array[i]);
for (i =0; i < size; i++)
for (j = 0; j < i; j++)
if (Array[j] > Array[i])
{
temp = Array[j];
Array[j] = Array[i];
for (k = i ; k > j ; k-- )
Array[k] = Array[k - 1] ;
Array[k + 1] = temp ;
}
printf ("\n Your Array has been insertion_sorted and should know look like this: \n");
for (int i = 0; i < size; i++)
printf("%d ", Array[i]);
printf("\n Would you like to search for a specific value? (Yy/Nn) \n");
answ = _getch();
if (answ == 'Y' || answ == 'y')
{
printf("Specify number to be searched \n");
scanf_s("%s", query);
xx = atoi(query);
printf("Searching for %d ", query);
for(h = 0; h < sizeof(Array); h++)
if (Array.at(h) == xx)
printf("%d\n", h);
else
printf("No such number was found in a sorted array\n");
}
Array.clear();
return 0;
}
int main()
{
insertion_sort();
return 0;
}
PS ignore the _asm part: it works, but hasn’t been used yet 🙂
printf("Searching for %d ", query);Sincequeryis declared an array ofchar, you shouldn’t use the%dspecifier which is used to print signed integers, change%dto%sorquerytoxx. Since this is C++, I would usestd::coutthough.sizeof(Array)doesn’t do what you want it to do. UseArray.size()instead.In C++, you don’t have to declare all your variables at the beginning of the function. That was an old part of C89 I believe. This means you can declare your for loop like this
for(int h = 0; h < Array.size(); h++)for example.Here is a good example of trying to find something in a vector:
You are mixing C and C++ code. I would recommend choosing one language and using only that language.