Go Down

### Topic: Sorting an array (Read 1 time)previous topic - next topic

#### Archelon

##### Feb 02, 2013, 08:01 pm
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: [Select]
`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

#### Arrch

#1
##### Feb 02, 2013, 08:04 pm
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.

#### robtillaart

#2
##### Feb 02, 2013, 08:05 pm
something like this
Code: [Select]
`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;}`
Rob Tillaart

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

Go Up

Please enter a valid email to subscribe