Bubble Sort algorithm

Algorithm Solution

I think my solution is better than the traditional way taught by many tutorials.

// initialise an array
int arr[9] = {4, 2, 8, 0, 5, 7, 1, 3, 9};

// the number of times each round needs to be compared and
// the total number of rounds to be compared
int n = sizeof(arr) / sizeof(arr[0]) - 1;

// initialse an integer for later swaps
int temp;

while (n--)
{
    for (int i = 0; i < n; i++)
    {
        if (arr[i] > arr[i + 1])
        {
            //swaping these two integers
            temp = arr[i];
            arr[i] = arr[i + 1];
            arr[i + 1] = temp;
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Leetcode Problem 75

Description

Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.

You must solve this problem without using the library's sort function.

Example 1:

Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Example 2:

Input: nums = [2,0,1]
Output: [0,1,2]
1
2
3
4
5
6

Constraints:

n == nums.length
1 <= n <= 300
nums[i] is either 0, 1, or 2.
1
2
3

Follow up: Could you come up with a one-pass algorithm using only constant extra space?

Solution

Last Updated: 8/4/2023, 12:30:20 PM
Contributors: oddnaveed