Categories
data structures java selection sort

selection sort

In this post, We will learn about the selection sort algorithm in the java language. It is a comparison-based sorting algorithm

Selection sort will select the element from an array, and keep on compare with the remaining elements.

End of each iteration we will obtain the minimum value, After that we will swap the minimum element to the sorted array

Likewise, it will select all the elements in the array and compare them with the remaining element

Unsorted Input array: [ 12, 4, 6, 7, 2, 5 ]
Sorted Output array:  [ 2, 4, 5, 6, 7, 12 ]

Execution Steps

  1. [2, 4, 6, 7, 12, 5]
  2. [2, 4, 6, 7, 12, 5]
  3. [2, 4, 5, 7, 12, 6]
  4. [2, 4, 5, 6, 12, 7]
  5. [2, 4, 5, 6, 7, 12]

Selection Sort

Time Complexity : O(n^2)

Code

package example;

import java.util.Arrays;

public class SelectionSort {

	private void sortArray(int[] arr) {

		for (int i = 0; i < arr.length; i++) {
			int selectionItem = i;
			for (int j = i + 1; j < arr.length; j++) {
				if (arr[j] < arr[selectionItem]) {
					selectionItem = j;
				}
			}
			int temp = arr[selectionItem];
			arr[selectionItem] = arr[i];
			arr[i] = temp;
		}
	}

	public static void main(String[] args) {
		int[] arr = { 12, 4, 6, 7, 2, 5 };
		SelectionSort selectionSort = new SelectionSort();
		selectionSort.sortArray(arr);
		System.out.println(Arrays.toString(arr));
	}
}

Output

[2, 4, 5, 6, 7, 12]

Related Articles

Categories
Bubble sort data structures java

bubble sort algorithm

In this post, we will learn about the bubble sort algorithm. The bubble sort algorithm is one of the important sorting algorithms

It will compare two adjacent elements in an array and swap the right value to the left if it is lesser than left

Bubble Sort

Time Complexity: O(n^2)
Values1012462
Position01234
Input Array
Step 1
Iterate the given array using for loop
Step 2 
Add one more iteration within the for loop again
Step 3
compare the first element with second element
Step 4 
If first element greater than second element swap the two elements
Step 5 
Compare the second element with third element 
Step 6
If Second element is greater than third element, then swap the two elements 
Step 7 
Continue until nth element 
Step 1
Step2
Step 3
Step 4
Result of the first iteration

Java Implementation


public class BubbleSort {

	private void sortArray(int arr[]) {
		for (int i = 0; i < arr.length; i++) {
			boolean isSwap = false;
			for (int j = 0; j < arr.length - i - 1; j++) {
				if (arr[j] > arr[j + 1]) {
					int temp = arr[j + 1];
					arr[j + 1] = arr[j];
					arr[j] = temp;
					isSwap = true;
				}
			}
			if (!isSwap) {
				break;
			}
		}
	}

	public static void main(String[] args) {
		int arr[] = { 10, 12, 4, 6, 2 };
		System.out.println("Array Before sorting");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "  ");
		}
		BubbleSort bubbleSort = new BubbleSort();
		bubbleSort.sortArray(arr);

		System.out.println("\nArray After Sorting");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "  ");
		}

	}

}

Output

Array Before sorting
10  12  4  6  2  
Array After Sorting
2  4  6  10  12  
Categories
collections java

sorting operations in java using streams

In this example, we learn sorting operations in java using streams

In Java 8 it is easy to sort records from an arraylist

Streams API providing powerful features to sort the records from a list without modifying it

This will returns a stream consisting of the sorted elements

Syntax

Stream sorted()
list.stream().sorted({operations});

Ascending Example

import java.util.ArrayList;
import java.util.List;

public class AscendingSortingStreams {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("Ball");
        list.add("Apple");
        list.add("Cat"); // printitng values before sorting
        System.out.println("Values before sorting ");
        list.stream().forEach(x -> System.out.println(x));
        System.out.println("*** Values After sorting ***");
        list.stream().sorted().forEach(x -> System.out.println(x));
    }
}

Output

Values before sorting 
Ball
Apple
Cat
*** Values After  sorting ***
Apple
Ball
Cat

Descending Example

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class DescendingSortingStreams {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("Ball");
        list.add("Apple");
        list.add("Cat");
        // printitng values before sorting
        System.out.println("Values before sorting ");
        list.stream().forEach(x -> System.out.println(x));
        System.out.println("*** Values After sorting ***");
        // Comparator.reverseOrder() will sort the records in descending order
        list.stream().sorted(Comparator.reverseOrder()).forEach(x -> System.out.println(x));
    }
}

Output

Values before sorting 
Ball
Apple
Cat
*** Values After  sorting ***
Cat
Ball
Apple

References

Oracle Docs

Related Articles

filter operations in streams on java 

Iterate list using streams in java

Categories
collections java

Sort an Arraylist in java with example

In this tutorial, we will learn how to Sort an Arraylist in java with example by ascending order using collections class

If you are new to array list refer below link to understand array list
https://beginnersbug.com/arraylist-in-java/

Features

  • Sort the specified list into ascending order,
  • This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
  • The specified list must be modifiable, but need not be resizable.

Syntax

Collections.sort(list);

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortArrayListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList();
        list.add("Car");
        list.add("Zebra");
        list.add("Apple");
        list.add("Ball");
        System.out.println("Array list values before sorting \n");
        for (String string : list) {
            System.out.println("Value is " + string);
        }
        // Below sort method will sort your list
        Collections.sort(list);
        System.out.println("\nArray list values after sorting \n");
        for (String string : list) {
            System.out.println("Value is " + string);
        }
    }
}

Output

Array list values before sorting 

Value is Car
Value is Zebra
Value is Apple
Value is Ball

Array list values after sorting 

Value is Apple
Value is Ball
Value is Car
Value is Zebra

Reference

https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html

Related Articles

iterate stream with index in Java8

foreach in java8 using streams