Javatpoint Logo
Javatpoint Logo

Bubble Sort

In Bubble sort, Each element of the array is compared with its adjacent element. The algorithm processes the list in passes. A list with n elements requires n-1 passes for sorting. Consider an array A of n elements whose elements are to be sorted by using Bubble sort. The algorithm processes like following.

  1. In Pass 1, A[0] is compared with A[1], A[1] is compared with A[2], A[2] is compared with A[3] and so on. At the end of pass 1, the largest element of the list is placed at the highest index of the list.
  2. In Pass 2, A[0] is compared with A[1], A[1] is compared with A[2] and so on. At the end of Pass 2 the second largest element of the list is placed at the second highest index of the list.
  3. In pass n-1, A[0] is compared with A[1], A[1] is compared with A[2] and so on. At the end of this pass. The smallest element of the list is placed at the first index of the list.

Algorithm :

  • Step 1: Repeat Step 2 For i = 0 to N-1
  • Step 2: Repeat For J = i + 1 to N - I
  • Step 3: IF A[J] > A[i]
    SWAP A[J] and A[i]
    [END OF INNER LOOP]
    [END OF OUTER LOOP
  • Step 4: EXIT

Complexity

Scenario Complexity
Space O(1)
Worst case running time O(n2)
Average case running time O(n)
Best case running time O(n2)

C Program

Output:

Printing Sorted Element List . . . 
7
9
10
12
23
34
34
44
78 
101

C++ Program

Output:

Printing Sorted Element List ...
7
9
10
12
23
23
34
44
78
101

Java Program

Output:

Printing Sorted List . . . 
7
9
10
12
23
34
34
44
78 
101 

C# Program

Output:

Printing Sorted Element List . . . 
7
9
10
12
23
34
34
44
78 
101 

Python Program

Output:

Printing Sorted Element List . . . 
7
9
10
12
23
34
34
44
78 
101 

Rust Program

Output:

Printing Sorted Element List . . . 
7
9
10
12
23
34
34
44
78 
101
4 

JavaScript Program

Output:

Printing Sorted Element List ...
7
9
10
12
23
23
34
44
78
101

PHP Program

Output:

Printing Sorted Element List ...
7
9
10
12
23
23
34
44
78
101

Next TopicBucket Sort




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA