Skip to main content

Posts

Showing posts with the label lambda expressions

Java code of Insertion sort

Introduction Insertion sort is the best sorting algorithm for small-sized list of elements as compared to selection sort and bubble sort . This sorting algorithm always maintains a sorted sublist within an iteration i.e. it finds the correct position of a single element at a time and inserts it in its correct position within the currently sorted sublist. Worst Complexity    : O(n*n) Best Complexity        : O(n) Average Complexity : O(n*n) Imperative style using Java 7 public class InsertionSortExample { private static int array[] = {0,5,2,6,3,1,-9}; public static void main(String[] args) { insertionSortAscending(); System.out.println("Ascending Sorted List"); for(int value : array) { System.out.print(value + " "); } insertionSortDescending(); System.out.println("\nDescending Sorted List"); for(int value : array) { System.out.print(value + " "); } } private static void insertionSortAscending() {

Java Bubble Sort Example

Introduction Bubble sort is the simplest sorting algorithm. It has the following steps a) Iterates through the list b) Compares the adjacent elements c) Swap the adjacent elements if they are in not in proper sorting order d) The list is traversed repeatedly unless the list is sorted Worst Complexity : O(n*n) Best Complexity    : O(n) Alternate name      : Sinking Sort Implementation using Simple Loops public class BubbleSortExample { private static int array[] = {0,5,2,6,3,1}; static int temp = 0; public static void main(String[] args) { bubbleSortAscending(); System.out.println("Ascending Sorted List"); for(int value : array) { System.out.print(value + " "); } bubbleSortDescending(); System.out.println("Descending Sorted List"); for(int value : array) { System.out.print(value + " "); } } private static void bubbleSortAscending() { for(int outer=0; outer<array.length; outer++) {