Sorting Array
Sorting is one of the most fundamental operations in programming. In this post, we’ll look at how to sort an array in ascending order using a simple nested loop approach. This method is often referred to as the Bubble Sort or Selection Sort style sorting.
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(arr[i]>arr[j]){
int temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
}
for(int i:arr){
System.out.print(i);
}
}
}
ow the Code Works
Input:
- The program reads the size of the array (
n) and then the elements of the array.
- The program reads the size of the array (
Sorting Logic:
- A nested loop is used to compare every element with the others.
- If an element at
arr[i]is greater thanarr[j], the two elements are swapped to bring smaller elements to the left.
Output:
- The sorted array is printed in ascending order.
Example Input and Output
Input:
Process:
- Original Array: [4, 2, 5, 1, 3]
- After Sorting: [1, 2, 3, 4, 5]
Output:
How the Sorting Works
The sorting algorithm iterates through the array multiple times:
Step 1:
- Compare each element with the next one.
- Swap if the current element is larger than the next.
Step 2:
- Repeat the process for all remaining elements.
This ensures that the smallest element moves to the front first, followed by the next smallest, and so on.
Key Points
Time Complexity:
- The nested loop makes this algorithm O(n²), where
nis the size of the array. - This is not efficient for large datasets but is simple and useful for small arrays.
- The nested loop makes this algorithm O(n²), where
Space Complexity:
- The algorithm uses no additional space, making it O(1) in terms of space complexity.
Edge Cases:
- Already Sorted Array: The program will still perform comparisons unnecessarily.
- Empty Array: If
n == 0, the program will output nothing, which is correct behavior.