0

I have written a sorting algorithm. What is the name of this algorithm?

void sort(int *arr, size_t len) {
    int flag = 1, temp;
    while (flag != 0) {    
        flag = 0;
        for (int i = 0, j = 1; i < len - 1; i++, j++) {
            if (arr[i] > arr[j]) {
                flag = 1;
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}
6
  • 3
    Do you need that outer loop checking if flag != 0? Wouldn’t while (true) be clearer? Commented Aug 4, 2022 at 15:10
  • The if (flag != 2) break; is redundant, and should be removed. Set flag = 0 before the for loop, and flag = 1 inside the for loop. That way, the while loop will end when no swaps were made. Commented Aug 4, 2022 at 15:15
  • @Satyam S This algorithm is called "bad style of programming". At least it can invoke undefined behavior. Commented Aug 4, 2022 at 15:19
  • @VladfromMoscow ? Commented Aug 4, 2022 at 15:39
  • It's a rather bad variant of bubble sort. It finishes when there are no swaps in a pass, which is good, but it doesn't reduce the size of each pass, which is bad. Also, it fails horribly if len is 0. Commented Aug 4, 2022 at 16:18

1 Answer 1

4

This is bubble sort: repeatedly loop over an array swapping adjacent elements and stop when nothing is swapped.

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.