Daa 1
Daa 1
Experiment no.1
b) Insertion Sort :
a) Bubble Sort :
1. Initializing: Start the sorting with 1st element present in the list.
2. Compare and Swap: Compare the current element to the next one. If the current element is
larger than the next, swap them.
3. Repetition: Repeat the process until the largest element present in the list moves to the end.
4. Iteration: repeat the process for the next element excluding the last sorted element.
Pseudo Code :
BubbleSort(array)
n = length(array)
for i = 0 to n-1 do
for j = 0 to n-i-2 do
if array[j] > array[j+1] then
// Swap array[j] and array[j+1]
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp
end if
end for
end for
end BubbleSort
b) Insertion Sort :
1. Initialization: Begin with the second element, as the first is trivially sorted.
2. Key Elements: Take the next element as the "key" and compare it to the elements in the
array's sorted segment (to the left of the key).
3. Shifting: Shift all items greater than the key to the right, making room for the key.
4. Insert Key: insert key into its desired position.
5. Iteration: repeat the process for all elements present in the list until the list is sorted.
Pseudo Code :
InsertionSort(array)
n = length(array)
for i = 1 to n-1 do
key = array[i]
j = i - 1
// Move elements of array[0..i-1] that are greater than
key
// to one position ahead of their current position
while j >= 0 and array[j] > key do
array[j + 1] = array[j]
j = j - 1
end while
array[j + 1] = key
end for
end InsertionSort
a) Bubble Sort :
a) Bubble Sort :
CODE:
import java.util.Scanner;
scanner.close();
}
RESULT:
b) Insertion Sort :
CODE:
import java.util.Scanner;
scanner.close();
}
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
// Move elements that are greater than key one position ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
}
RESULT:
5. Conclusion:
In the lab experiment, we implemented and analyzed sorting algorithms in Java: Bubble sort and
insertion sort. By calculating the run time complexities of these 2 algorithms we understand their
varying efficiencies. Bubble Sort and Insertion Sort are both useful educational tools for understanding
sorting methods, although they are rarely utilized for large-scale data due to their quadratic time
complexity. Insertion Sort is chosen over Bubble Sort because it is more efficient at managing little or
partially sorted data. For handling the large datasets, we use more defined sorting algorithms such as
Quick Sort, Heap Sort.