user1883003
user1883003

Reputation: 57

Searching, sorting and printing a sorted 2D array of integers in C

I am having trouble in printing the location of the maximum in a 2d array of integers. i.e. the element array[33][2] with value 500 is maximum, where [33] signifies the 33rd week and [2] signifies the 2nd day. I want to printf (" The maximum is 500 and is found on day : X") as well as printf (" The greatest week is : Y") (for the week one it is the greatest sum of the seven consecutive days within the week that is achieved)

Also, when I try to sort the 2D array of integers, the print of the sorted version is not sorted... I'm using bubble sort with temp:

for (i=0; i<100;i++){
for(j=0;j<7;j++){
fscanf(filetoreadfrom,"%d\n",&array[i][j]);

    if(array[i][j] < array[i][j+1]){

    temp=array[i][j];
    array[i][j]=array[i][j+1];
    array[i][j+1]=temp;
    }}}

I am lost...

Upvotes: 0

Views: 2021

Answers (3)

1&#39;&#39;
1&#39;&#39;

Reputation: 27095

In bubble sort, you have to keep looping over the entire array until you don't have to swap any elements on a particular loop. You only loop once, which won't work unless the array is almost sorted to begin with.

Also, you don't read in element [i][j+1] until after the loop for [i][j] is finished, so you're comparing [i][j] to whatever garbage is stored in [i][j+1]. Read in all your elements before sorting them!

Upvotes: 0

user1890202
user1890202

Reputation: 50

Just a few random thoughts: Indexing always begins with 0. There's no need to sort to find the largest number. Have you considered the possibility that to days or weeks might have the same value? If you sort an array how do you expect to know where the data was to begin with?

Good luck!

Upvotes: 1

perreal
perreal

Reputation: 97938

You are sorting the data before reading all of it. First read the data:

for (i=0; i<100;i++){
  for(j=0;j<7;j++){
    fscanf(filetoreadfrom,"%d\n",&array[i][j]);
  }
 }

Then do the sorting:

for (i=0; i<100;i++){
  for(j=0;j<7;j++){
    if(array[i][j] < array[i][j+1]){
      temp=array[i][j];
      array[i][j]=array[i][j+1];
      array[i][j+1]=temp;
    }
  }
}

And your sort algorithm is not correct. For example, when j is 6, the statement array[i][j]=array[i][j+1]; tries to read array[i][7].

Upvotes: 2

Related Questions