Pages: [1]   Go Down
Author Topic: Sorting an array  (Read 307 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Full Member
***
Karma: 0
Posts: 116
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello,
I've just come up with an own bubble sort function which sorts different numbers in a passed array in descending order and the function looks like this:
Code:
long bubbleSort(long sortedData[arraySize]) {


  long unsortedData[arraySize];
     for (int i = 0; i < arraySize-1; i++) {
    for (int c = 0; c + i <= arraySize-1; c++)
 {
   if(sortedData[i+c] < sortedData[i])
   {
     unsortedData[i] = sortedData[i+c];
    unsortedData[i+c] = sortedData[i];
   sortedData[i] = unsortedData[i];
  sortedData[i+c] = unsortedData[i+c];
    }
   
 }

}

return (sortedData[(arraySize/2)-1]+sortedData[arraySize/2])/2;
}

The code nicely sort the data and then in this case returns the average values of the two middle values but that doesn't really matter here.
WHAT I need help with is to identify what original place the biggest number had in the beginning.
Let me give you an example,
If i send this array,
 long OriginalArray[arraySize];
OriginalArray[0] = 111;
OriginalArray[1] = 51;
OriginalArray[2] = 400;
OriginalArray[3] = 3;

I want the function to first sort the numbers like this(which it already does):
400
111
51
3

And then tell me that the biggest number had slot number 2 in the original array.
Is there a way to easily implement this into my bubblesort function.
Thank you very much!
/Archie
Logged

California
Offline Offline
Faraday Member
**
Karma: 82
Posts: 3123
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Just do a scan before the bubble sort in the same function. A single for loop that keeps track of the highest number and it's index would suffice.
Logged

Global Moderator
Netherlands
Offline Offline
Shannon Member
*****
Karma: 168
Posts: 12428
In theory there is no difference between theory and practice, however in practice there are many...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

something like this
Code:

int findPositionLargest(long data[], int arraySize)
{
  int pos = 0;
  long largest = data[0];
  for (int i=0; i<arraySize; i++)
  {
    if (largest < data[i])
    {
      largest = data[i];
      pos = i;
    }
  }
  return pos;
}
Logged

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Pages: [1]   Go Up
Jump to: