0

While browsing old code I had written in freshman year of college, I found the following snippet marked as 'bubble sort'. (here n is the size of the array; eg. for an array of 10 elements n = 10).

for(int i = 0; i < n; i++)
    for(int j = i + 1; j < n; j++) {
        if(arr[i] > arr[j]) {
            int temp  = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }

Now, i can tell that this certainly isn't bubble sort, but maybe a very poor implementation of it. Fact is it works and I'm curious if this is an algorithm that already exists or if it is something that I came up on my own albeit it being very inefficient.

5
  • 1
    It's a selection sort with extra useless swaps Commented Dec 8, 2018 at 17:27
  • 1
    Your first sort implementation you learn at school. To teach you what is slow.. Commented Dec 8, 2018 at 17:35
  • 1
    @RaymondNijland Bubble sort only uses one index since it compares adjacent pairs. That is not the case here. Commented Dec 8, 2018 at 17:35
  • 1
    @RaymondNijland I don't see how. The inner loop is from 1 to n-j (which would be n-i here), and the comparison is between [i] and [i-1], not [i] and [j]. If what you mean is that there are two (nested) loops and a swap, then I've got news for you: a whole lot of sorting algorithms match that description. Commented Dec 8, 2018 at 17:48
  • well geuss iám wrong in this case and seriously need some caffaine to wake up @Nelfeal this indeed looks more like selection sort algorithm indeed Commented Dec 8, 2018 at 18:21

1 Answer 1

4

This is a poor implementation of selection sort. Take a reference implementation (from Wikipedia):

for (j = 0; j < n-1; j++) {
    int iMin = j;
    for (i = j+1; i < n; i++) {
        if (a[i] < a[iMin]) {
            iMin = i;
        }
    }

    if (iMin != j) {
        swap(a[j], a[iMin]);
    }
}

Instead of finding the minimum in the unsorted part and placing it at the end of the sorted part with a swap, your snipper just swaps everytime it finds a "potential minimum", that is a value lesser than the one past the end of the sorted part. That's inefficient because swaps simply cost more than index assignment.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.