Array Output/Bubble Sort Issue

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Prosdo
    New Member
    • Nov 2007
    • 32

    #1

    Array Output/Bubble Sort Issue

    Hi guys. I have a final program for school and the assignment is to show the top 5 numbers for the Cash 5 lottery over the past few days. I think I have all my loops right.I think I have the output listed correctly but it is duplicating on the output. Like the last time I ran it, it came up with the results:
    12
    12
    12
    12
    20

    I am starting to think the bubble sort is written incorrectly. Any help would be greatly appreciated. Here is the code:

    Code:
    #include <iostream.h>
    #include <stdlib.h>
    #include <string>
    using namespace std;
    int x;
    int y;
    int row;
    int col;
    int days[5][5];
    int ranks[40][2];
    int number_hold;
    int occur_hold;
    
    int main()
    {
    cout<<"Please enter the numbers for the Cash 5 for the past 5 days.(1-39 only)"<<'\n';
    cout<<"Start with the 1st number of day 1 and continue to last number of day 5."<<'\n';
    cout<<"Press enter after each number."<<'\n';
    int x = 0;
    for(x=0;x<40;x++)
    {
    ranks[x][0]=x;
    ranks[x][1]=0;
    }
    for(row=0;row<5;row++)
    {
    for(col=0;col<5;col++)
    {
    cin>>days[row][col];
    }
    }
     //Bubble Sort
    for(row=0;row<5;row++)
    {
    for(col=0;col<5;col++)
    {
    ranks[days[row][col]][1]+=1;
    }
    }
    
    //Occur Loop
    for(x=1;x<39;x++)
    {for(y=1;y<39;y++)
    {
    if(ranks[y][1]<ranks[y+1][1])
    {number_hold = ranks[y][0];
    occur_hold = ranks[y][1];
    ranks[y][0] = ranks[y+1][0];
    ranks[y][1] = ranks[y+1][1];
    ranks[y+1][1] = number_hold;
    ranks[y+1][1] = occur_hold;
    }
    }
    }
    cout<<"The top five numbers for the Cash 5 are:"<<'\n';
    cout<<ranks[1][0]<<'\n';
    cout<<ranks[2][0]<<'\n';
    cout<<ranks[3][0]<<'\n';
    cout<<ranks[4][0]<<'\n';
    cout<<ranks[5][0]<<'\n';
    
    
    
          system("PAUSE");
          return 0;
    }
  • RRick
    Recognized Expert Contributor
    • Feb 2007
    • 463

    #2
    A couple of things are going on. Line 50 has a bug with the second indice. Also, your sorting loop ranges are off. You want to go from 0 to the next to last index.

    There is way to speed this up. Since you only need the 5 biggest values, your outer loop only needs to be done 5 times. This is because each bubble iteration moves the greatest/smaller value to the end. Currently, you move the smallest value to the bottom, but now we want the largest value at the top. Your innner loop would look something like: [code=cpp]
    for(y=39;y>0;y--)
    {
    if(ranks[y-1][1]<ranks[y][1])
    [/code]
    Now you are switching the positions at y and y-1.

    Comment

    Working...