Java program to sort array using temporary variable

Program

import java.util.Scanner;
public class SortArrayUsingTempVariable {
  private void sortUsingTemp(int array[]) {
    for (int i = 0; i < array.length; i++) {
      for (int j = i + 1; j < array.length; j++) {
        int temp = 0;
        if (array[i] > array[j]) {
          temp = array[i];
          array[i] = array[j];
          array[j] = temp;
        }
      }      
      System.out.println(array[i]);    
    }
  }
  public static void main(String[] args) {
    int i = 0;
    System.out.println("Enter the required size of the array: ");
    Scanner reader = new Scanner(System.in);
    int size = reader.nextInt();
    int inputArray[] = new int[size];
    System.out.println("Enter the elements of the array: ");
    for (i = 0; i < size; i++) {
      inputArray[i] = reader.nextInt();
    }
    SortArrayUsingTempVariable sortArrayUsingTempVariable = new SortArrayUsingTempVariable();
    System.out.println("Array elements sorted in ascending order: ");
    sortArrayUsingTempVariable.sortUsingTemp(inputArray);
  }
}

This program demonstrates how to sort an array in ascending order using nested loops and a temporary variable. It is useful for learning the basics of sorting algorithms and understanding the role of comparisons and swaps in sorting operations.

  1. Input Handling:

    • The user is prompted to enter the size of the array.
    • The array elements are then provided by the user.
  2. Sorting Logic:

    • The program uses two nested for loops to compare each element of the array.
    • If the current element is greater than the next, their values are swapped using a temporary variable (temp).
    • This approach effectively implements a simple bubble sort.
  3. Output:

    • Each element of the sorted array is printed as the sorting progresses.
  4. Key Notes:

    • The sorting process arranges the elements in ascending order by repeatedly swapping adjacent elements that are out of order.
    • Time complexity is O(n²), making it less efficient for large arrays.

Key Features:

  1. Manual Sorting:
    • The program illustrates the logic of sorting through comparison and swapping.
  2. Simplicity:
    • Easy to understand for beginners learning sorting algorithms.

Limitations:

  • Inefficient for large arrays due to O(n²) time complexity.

Output

javac .\SortArrayUsingTempVariable.java
java SortArrayUsingTempVariable        
Enter the required size of the array: 
5 
Enter the elements of the array: 
100
54
76
12
4
Array elements sorted in ascending order: 
4
12
54
76
100