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

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:
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):

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!

Offline Offline
Faraday Member
Karma: 92
Posts: 3441
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.

Global Moderator
Offline Offline
Shannon Member
Karma: 223
Posts: 13870
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

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 -,77.0.html -
(Please do not PM for private consultancy)

Pages: [1]   Go Up
Jump to: