Passing arrays through functions w/bubble sort.
May 14, 2013 at 10:15pm UTC
My Assignment:
Create two arrays data and sdata. Input user data into array data. Copy the contents of array data into sdata. Then bubble sort the array sdata in ascending order. Then display the contents of array data and sdata. Use four void functions for input, copying, sorting and displaying.
Current Problem:
I can't figure out why my array data[] is being displayed out of the original order that it was input via input function. Any hints as to why this is happening? I've been stuck on this for several hours now...any help is appreciated.
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
#include <iostream>
using namespace std;
//input function
void input(double x[], int length)
{
for (int i = 0; i < length; i++)
{
cout << "Enter a score: " ;
cin >> x[i];
}
}
//copy function
void copy(double source[], double dest[], int length)
{
for (int i = 0; i < length; i++)
{
dest[i]=source[i];
}
}
//sort function
void sort(double x[], int length)
{
double temp;
for (int j = (length - 1); j > 0; j--)
{
for (int i = 1; i < length; i++)
{
if (x[i-1] > x[i])
{
temp = x[i];
x[i] = x[i-1];
x[i-1] = temp;
}
}
}
}
//display function
void display(double x[], int length)
{
for (int i = 0; i < length; i++)
{
cout << x[i] << ' ' ;
}
}
int main()
{
//declare & initialize variables
int maxLength = 0;
double data[maxLength];//original array
double sdata[maxLength];//sorted array
cout << "Please enter the data item count <1-20>: " ;
cin >> maxLength;
cout << endl;
if (maxLength > 0 && maxLength < 21)//validate item count
{
input(data, maxLength);//call void input function
}
else
cout << "\nItem count is NOT within required range.\nRequired range is 1 to 20.\n" ;
copy(data, sdata, maxLength);
sort(sdata, maxLength);
//display the data within the arrays
cout << "\nOriginal Data: " ;
display(data, maxLength);
cout << "\nSorted Data: " ;
display(sdata, maxLength);
cout << endl;
return (0);
}
Last edited on May 14, 2013 at 10:15pm UTC
May 14, 2013 at 10:32pm UTC
I'm using Code::Blocks 10.05 and listening to Caravan Palace...
May 14, 2013 at 11:18pm UTC
Ugh. I moved the display(data,maxLength) above the copy/sort calls and everything is working now.
Topic archived. No new replies allowed.