Posts

Showing posts with the label java algorithms

Implement Quick Sort in Java.

Image
*QuickSort:             Quicksort or partition-exchange sort, is a fast sorting algorithm, which is using divide and conquer algorithm. Quick sort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quick sort can then recursively sort the sub-lists. Steps to implement Quick sort: 1) Choose an element, called pivot, from the list. Generally pivot can be the middle index element or u can choose any. 2) Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation. 3) Recursively apply the above steps to the sub-list of elements with smaller values and separately the sub-list of elements with greater values. //Write a Java program to implement quick sort algorithm. public clas...

Implement Insertion Sort algorithm in Java.

Image
*Insertion Sort:             Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. * Advantages of Insertion Sort:   1) It is very simple. 2) It is very efficient for small data sets. 3) It is stable; i.e., it does not change the relative order of elements with equal keys. 4) In-place; i.e., only requires a constant amount O(1) of additional memory space.           Insertion sort iterates through the list by consuming one input element at each repetition, and growing a sorted output list. On a repetition, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain. //Write a Java program to implement insertion sort. public class MyInsertionSort {      public static void main(String a[]){      ...