16 May 2024

Sorting Array

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

  1. Input:

    • The program reads the size of the array (n) and then the elements of the array.
  2. Sorting Logic:

    • A nested loop is used to compare every element with the others.
    • If an element at arr[i] is greater than arr[j], the two elements are swapped to bring smaller elements to the left.
  3. Output:

    • The sorted array is printed in ascending order.

Example Input and Output

Input:


5 4 2 5 1 3

Process:

  • Original Array: [4, 2, 5, 1, 3]
  • After Sorting: [1, 2, 3, 4, 5]

Output:


1 2 3 4 5

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

  1. Time Complexity:

    • The nested loop makes this algorithm O(n²), where n is the size of the array.
    • This is not efficient for large datasets but is simple and useful for small arrays.
  2. Space Complexity:

    • The algorithm uses no additional space, making it O(1) in terms of space complexity.
  3. 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.

 

No comments:

Post a Comment