Skip to main content

Posts

Showing posts with the label bubble sort

Scala language implementation of Bubble Sort

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 package main.scala object BubbleSort { val array = Array(0,5,2,6,3,1) def main (args : Array[String] ) { print("Unsorted List ") println(array.toList) print("Ascending sorted List ") bubbleSortAscending; println(array.toList) bubbleSortDescending print("Descending sorted List ") println(array.toList) } def bubbleSortAscending { //in scala you can combine inner and outer loops, until does not include the last number for( i <- 0 until array.length; j <- 1 until array.le

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++) {