0% found this document useful (0 votes)
27 views4 pages

Java Bubble Sort Program Example

Uploaded by

Suneel Ramireddy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views4 pages

Java Bubble Sort Program Example

Uploaded by

Suneel Ramireddy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Sorting Array:

Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in the wrong order. This algorithm is not suitable for large data sets as its
average and worst-case time complexity are quite high.
 We sort the array using multiple passes. After the first pass, the maximum element
goes to end (its correct position). Same way, after second pass, the second largest
element goes to second last position and so on.
 In every pass, we process only those elements that have already not moved to correct
position. After k passes, the largest k elements must have been moved to the last k
positions.
 In a pass, we consider remaining elements and compare all adjacent and swap if larger
element is before a smaller element. If we keep doing this, we get the largest (among
the remaining elements) at its correct position.
Program for Bubble Sort in Java
class BubbleSort {
void bubbleSort(int arr[])
{
int n = [Link];
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
// Driver method to test above
public static void main(String args[])
{
BubbleSort ob = new BubbleSort();
int a[] = { 64, 34, 25, 12 };
[Link](a);
int n = [Link];

for (int i = 0; i < n; ++i)


[Link](a[i] + " ");
[Link]();
}
}

Output
12 25 34 64
Selection Sort

Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly


selecting the smallest (or largest) element from the unsorted portion and swapping it with
the first unsorted element. This process continues until the entire array is sorted.
1. First we find the smallest element and swap it with the first element. This way we get
the smallest element at its correct position.
2. Then we find the smallest among remaining elements (or second smallest) and swap it
with the second element.
3. We keep doing this until we get all elements moved to correct position.

JAVA Program For Selection Sort:

public class SelectionSort {

public static void selectionSort(int[] arr) {


int n = [Link];

// One by one move boundary of unsorted subarray


for (int i = 0; i < n - 1; i++) {
// Find the minimum element in unsorted array
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}

// Swap the found minimum element with the first element


int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}

public static void main(String[] args) {


int[] arr = {64, 25, 12, 22, 11};
[Link]("Original array:");
for (int num : arr) {
[Link](num + " ");
}
[Link]();

selectionSort(arr);

[Link]("Sorted array:");
for (int num : arr) {
[Link](num + " ");
}
[Link]();
}
}

Insertion Sort
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element
of an unsorted list into its correct position in a sorted portion of the list. It is like sorting
playing cards in your hands. You split the cards into two groups: the sorted cards and the
unsorted cards. Then, you pick a card from the unsorted group and put it in the right place in
the sorted group.
 We start with the second element of the array as the first element is assumed to be
sorted.
 Compare the second element with the first element if the second element is smaller
then swap them.
 Move to the third element, compare it with the first two elements, and put it in its
correct position
 Repeat until the entire array is sorted.
// Java program for implementation of Insertion Sort
public class InsertionSort {
/* Function to sort array using insertion sort */
void sort(int arr[])
{
int n = [Link];
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
static void printArray(int arr[])
{
int n = [Link];
for (int i = 0; i < n; ++i)
[Link](arr[i] + " ");
[Link]();
}
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6 };

InsertionSort ob = new InsertionSort();


[Link](arr);
printArray(arr);
}
}

Common questions

Powered by AI

The initial arrangement of data significantly influences the efficiency of sorting algorithms. For example, Insertion Sort is highly efficient for nearly-sorted data because it only requires a linear scan to confirm the sorted order, resulting in a best-case time complexity of O(n). If the array is already or nearly sorted, Insertion Sort requires minimal data movement, which drastically improves its performance compared to more arbitrary arrangements .

In Selection Sort, the swapping mechanism moves the smallest unsorted element to its correct position in the front of the array by performing a single swap per pass. This minimizes the number of swaps compared to Bubble Sort, where multiple adjacent swaps can occur during each pass. The main distinction is that Selection Sort reduces swap operations to one per iteration, while Bubble Sort may involve several swaps in each pass to 'bubble up' the largest element .

The Bubble Sort algorithm stops processing further passes when it completes a pass without performing any swaps, indicating that the array is already sorted. During each pass, it repeatedly swaps adjacent elements if they are in the wrong order. If no swaps are needed in a pass, it means the remaining elements are already in the correct order, thus concluding the sort process .

Insertion Sort mimics the manual sorting of playing cards by separating the list into a sorted and an unsorted portion. It starts by considering the first card as sorted. It then picks each remaining card from the unsorted portion and places it into its correct position within the sorted portion, similar to how one would sort cards held in hand by repeatedly inserting the next unsorted card into the existing order .

In a nearly sorted array, Bubble Sort can take advantage of its design to quickly finish the sorting process because fewer swaps are needed to achieve the final sorted order. The algorithm iteratively compares adjacent elements, swapping where necessary, but if a pass is completed without swaps, it stops early. This characteristic allows Bubble Sort to essentially 'adapt' to the orderliness of the dataset for potentially shorter run times compared to a random arrangement, where it would need to perform multiple full passes of swaps .

Bubble Sort has the unique feature of being able to detect when the array is already sorted before completing all theoretical passes. If a complete pass is made without any swaps, it indicates that the array is sorted, allowing the algorithm to terminate early. This feature can lead to improved performance over other O(n^2) algorithms like Selection Sort that lack such early termination checks .

A potential limitation of Selection Sort compared to Insertion Sort when applied to nearly sorted datasets is its inability to exploit the sortedness of the input. Selection Sort does not change its number of operations based on input order since it does a full scan for the smallest element and a swap operation on each pass regardless of array order. In contrast, Insertion Sort performs efficiently on nearly sorted data by minimizing data movement through its iterative insertion mechanism, resulting in fewer operations and hence better performance .

Both Bubble Sort and Selection Sort have a worst-case and average time complexity of O(n^2), making them inefficient for large datasets. However, Bubble Sort's performance can slightly vary since it may terminate early if the array becomes sorted, whereas Selection Sort systematically goes through each remaining unsorted element even if the rest of the array is already sorted, which can make it comparatively more consistent but not faster .

Selection Sort ensures the smallest element is placed in its correct position by iterating over the unsorted portion of the array to find the smallest element and swapping it with the first unsorted element. This guarantees that with each pass, the smallest remaining element is moved to the sorted portion of the array. This process is repeated until the array is completely sorted .

Insertion Sort is often preferred over other simple sorting algorithms like Bubble Sort or Selection Sort for small datasets because it has a linear time complexity in the best case, where the data is nearly sorted. Its simplicity and efficiency in handling small-scale or partially sorted data make it a practical choice, as it involves less overhead and allows for quick, adaptive sorting .

You might also like