Reverse the order of an insertion sort?
Mar 20, 2014 at 1:40pm UTC
We have to write a code to randomly fill an array, then ask for an element, then sort the array specifically with an insertion sort, then cout them in ascending order. Buuuuuuut mine is descending. What did I do opposite?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
#include <iostream>
#include <iomanip>
#include <string>
#include <stdlib.h>
#include <math.h>
using namespace std;
int arrray[20];
int search(int arrray[20],int element);
void fill();
void display();
void sort(int arrray[]);
int main()
{
int window;
int num;
int result;
fill();
display();
cout << "\n" << endl;
cout << "What element are you searching for\?" << endl;
cin >> num;
result = search(arrray,num);
if (result != -1)
cout << "\nThe element was found at index " << result << "." << endl;
else
cout << "\nThe number was not found." << endl;
sort(arrray);
display();
cin >> window;
return 0;
}
void fill()
{
srand(1);
for (int i = 0; i < 20; i++)
{
arrray[i] = rand() % 100;
}
}
int search(int arrray[],int element)
{
int index;
for (index = 0; index < 10; index++)
{
if (element == arrray[index])
break ;
}
if (element == arrray[index])
return index;
else
return -1;
}
void display()
{
int num;
int result;
for (int x = 0; x < 20; x++)
cout << arrray[x] << " " ;
}
void sort(int arrray[])
{
int i, j, key, numLength = 20;
for (j = 1; j < numLength; j++)
{
key = arrray[j];
for (i = j - 1; (i >= 0) && (arrray[i] < key); i--)
{
arrray[i+1] = arrray[i];
}
arrray[i+1] = key;
}
return ;
}
Mar 20, 2014 at 2:01pm UTC
arrray[i] < key
Try >
Mar 21, 2014 at 1:29pm UTC
@keskiverto
Perfect! Thanks a bunch man!
Topic archived. No new replies allowed.