Bubble sort

I'm trying to write a function in a program to bubble sort an array. I'm not having any problems calling the function because i set it to cout from within the function and it does, but it's displaying the last number in the original array and not the number it should display if the bubble sort function performed correctly. I'm clearly getting something wrong with the bubble sort.

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
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>

using namespace std;

int i=0, total, j=0;
ifstream in_stream;
char sales_file[16];
double sales_average, sales[21], sum, highest_sales, lowest_sales, length;
void bubblesort(double sales[], double length);

int main()
{

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

cout << "What is the name of the file for the sales?\n";
cin >> sales_file;
in_stream.open(sales_file);
while(!in_stream.eof())
{
in_stream >> sales[i];
i++;
}
int num_of_locations = sales[0];

for (i=1; i<21; i++)
   {
      sum += sales[i];
      }

sales_average = sum / sales[0];

length = sales[0];

highest_sales = sales[20];

cout << "The total of all sales at all locations is " << sum << " .\n";
cout << "The average sales is " << sales_average << " per location.\n";

bubblesort(sales, length);


in_stream.close();

}

void bubblesort(double sales[], double length)
{
for (int i = length - 1; i > 0; i--)
   for (int j = 0; j < i; j++)
      if (sales[j] > sales[j+1])
      {
         double temp = sales[j];
         sales[j] = sales[j+1];
         sales[j+1] = temp;
         }
cout << sales[20];
         }
         
The correct BubbleSort function is :
1
2
3
4
5
6
7
8
9
10
11
12
void bubblesort(double sales[], double length)
{
	int i, j;
	for(i = 0; i < length; i++)
	for(j = 0; j < length - 1; j++)
	if(sales[j] > sales[j + 1])
	{
		double temp = sales[j];
		sales[j] = sales[j + 1];
		sales[j + 1] = temp;
	}
}
Last edited on
Topic archived. No new replies allowed.