Selection Sort
Selection Sort repeatedly selects the smallest element from the unsorted portion and moves it to the sorted portion.
Pseudo-Code:
for i from 0 to n-2:
minIndex = i
for j from i+1 to n-1:
if arr[j] < arr[minIndex]:
minIndex = j
swap arr[i] with arr[minIndex]
Complexity:
Bubble Sort
Bubble Sort repeatedly steps through the list, compares adjacent elements, and swaps them if necessary.
Pseudo-Code:
for i from 0 to n-2:
for j from 0 to n-2-i:
if arr[j] > arr[j+1]:
swap arr[j] with arr[j+1]
Complexity:
Linear Search
Linear Search checks each element in the array sequentially to find the target.
Pseudo-Code:
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
Complexity:
Binary Search
Binary Search finds an element in a sorted array by repeatedly dividing the search interval in half.
Pseudo-Code:
public static int binarySearch(int[] arr, int target) {
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
Choosing the right algorithm for sorting and searching is very important. For more detailed information, refer to the Notion link: