Learn-dsa..in 30 days!



























CC-1 : Implement Bubble Sort Algorithm.

Description:

Bubble Sort (also known as Sinking Sort) is one of the simplest sorting algorithms. It works by repeatedly iterating through the list, comparing adjacent elements and swapping them if they are not in the desired sort order. Given an input array, sort its elements using Bubble Sort.

Test cases and expected outputs:

Input Parameters Expected outputs
Array:
33, 3, 4, 97, 62, 122, 124, 20, 1,
Sorted Array:
1, 3, 4, 20, 33, 62, 97, 122, 124,

Pseudocode:

bubbleSort(nums[]):

Integer array named nums is received as input parameter.
Initialize boolean variable noSwap to false. If in an iteration of elements of array, no elements get swapped, it means the array is sorted. We will use variable noSwap to track if any elements got swapped in the current iteration.
Iterate through using for loop with iidx as iteration variable and values of iidx ranging from 0 to nums.length:
Set noSwap to false.
Iterate through using for loop with jidx as iteration variable and values of jidx ranging from 0 to (nums.length-iidx-1):
If nums[jidx] > nums[jidx+1], then swap order is wrong so swap the data at these indices.
If whole inner iteration is finished and noSwap is still 0, that means the array is already sorted and no further iterations are needed so we can return from the method.
The element of nums array have been sorted now using Bubble Sort, so return nums array from the method.

Code:

public int[] bubbleSort(int[] nums){
	boolean noSwap=true;
	for (int iidx=0;iidx < nums.length;iidx++) {
		noSwap=true;
		for (int jidx=0;jidx < nums.length-iidx-1;jidx++) {
			if (nums[jidx]>nums[jidx+1]) {
				int swap=nums[jidx];
				nums[jidx]=nums[jidx+1];
				nums[jidx+1]=swap;
				noSwap=false;
			}			
		}
		if(noSwap==true) {
			break;
		}
	}
	return nums;
}

Click here to download and run code and test cases !