Array sorting
Array sorting
class BubbleSort {
int n = a.length;
System.out.print(a[i]);
arr[j + 1] = temp;
Code Explanation:
1. Array Initialization:
2. Array Length:
int n = a.length;
The outer loop runs n - 1 times. Each iteration of this loop represents one "pass" through the
array.
After each pass, the largest unsorted element "bubbles up" to its correct position at the end of
the array.
n - i - 1 ensures that the algorithm doesn't re-check the already sorted elements at the end of the
array.
a[j + 1] = temp;
If the current element a[j] is greater than the next element a[j + 1], they are swapped.
This ensures that the larger element "bubbles up" toward the end of the array.
First Pass:
After the first pass, the largest element (64) is in its correct position.
Second Pass:
After the second pass, the second-largest element (34) is in its correct position.
Third Pass:
After the third pass, the third-largest element (25) is in its correct position.
Final Array:
Selection Sort
int n = arr.length;
System.out.print(arr[i]+" ");
int min_idx = i;
// is found
min_idx = j;
// correct position
arr[i] = arr[min_idx];
arr[min_idx] = temp;
System.out.print(arr[i]+" ");
}
1.Initialize the array and print the original array:
• The arr array is initialized with the values {64, 25, 12, 22, 11}.
• The outer loop iterates through each element of the array, considering it as the minimum
element (min_idx).
• The inner loop compares the current minimum element with the remaining unsorted
elements in the array.
• If a smaller element is found, the index of the new minimum element (min_idx) is
updated.
• After the inner loop completes, the minimum element found is swapped with the element
at the current position (i).
• This ensures that the smallest element is placed at the beginning of the unsorted portion
of the array.
• Steps 2-4 are repeated for the next position until the entire array is sorted.
Step 4: [11, 12, 22, 25, 64] // 25 is already in the correct position
Step 5: [11, 12, 22, 25, 64] // 64 is already in the correct position