0% found this document useful (0 votes)
11 views

Sorting Techniques5

Uploaded by

ravi gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Sorting Techniques5

Uploaded by

ravi gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Sorting Techniques

1. Bubble Sort

Sorting is  to place elements in increasing or decreasing order.  Bubble sort is also
known as sinking sort . In this sorting algorithm , we keep comparing the adjacent
pair , if they are in not right order , then they swapped each other position . When
there are no elements  swapped in one full iteration of element list , then it
indicates that bubble sort is completed.

When to Use

Bubble sort is good to use for small number of input elements(less than 1000) .
You can see  by running the below algorithm for
(Input)(Space)                     (Time taken)
10 elements           :           Bubble sort took   0  milliseconds
100 elements         :           Bubble sort took   1  milliseconds
1000 elements       :           Bubble sort took   2  milliseconds 
10000 elements     :   Bubble sort took    181 milliseconds
100000 elements   :       Bubble sort took    19096 milliseconds

Big O Notation

In simple words , Big O allows us to say something about how the size of inputs
affect the runtime of a program .This technique can also be applied to other
resources that an algorithm takes up (such as memory)
and we can analyze other bounds than the upper bound such as lower bound on
time or space or expected time or space that an algorithm takes up .

Properties

It is a stable algorithm i.e does not change the relative order of elements with
equal keys

Best , Average,Worst Cases

*  Best Case        :    O(n)


* Average Case   :    O(n^2)
* Worst Case      :    O(n^2)
* Worst Case (space complexity) :  O(1)

Algorithm:
i. Start
ii. Pass=1
iii. i=0
iv. Check that arr[i]>arr[i+1] if yes
Interchange arr[i] and arr[i+1]
v. i=i+1
vi. Check that i<=arr.length-pass goto step 4
vii. pass = pass+1
viii. Check that pass<arr.length, goto step 3
ix. Stop

Program:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

public class BubbleSort


{

public static int[] bubbleSort(int[] list)


{
for (int i = (list.length - 1); i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (list[j - 1] > list[j]) {
// swap elements at j-1 and j
int temp = list[j - 1];
list[j - 1] = list[j];
list[j] = temp;
}
}
}

return list;
}

public static void main(String args[]) throws Exception


{
String list="";
int i=0,n=0;

BubbleSort s= new BubbleSort();


ArrayList<Integer> arrlist=new ArrayList<Integer>();
System.out.println(" ");
System.out.println(" ");
System.out.println("Please enter the list of elements,one element per line");
System.out.println(" write 'STOP' when list is completed ");
BufferedReader bf=new BufferedReader(new
InputStreamReader(System.in));
while(!(list=bf.readLine()).equalsIgnoreCase("stop"))
{
int intelement=Integer.parseInt(list);
arrlist.add(intelement);

}
int elementlist[] = new int[arrlist.size()];
Iterator<Integer> iter = arrlist.iterator();
for (int j=0;iter.hasNext();j++) {
elementlist[j] = iter.next();
}
elementlist=bubbleSort(elementlist);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("Values after Bubble Sort : ");
for (int j=0;j<elementlist.length;j++) {
System.out.println(elementlist[j]+" ");
}
}
}

2. Selection Sort

Sorting is to place elements in increasing or decreasing order.  Selection sort is a


simple sorting algorithm  .

The algorithm divides the input lists into two parts ; the sublist of the items are
already sorted ,which is built up from left to right at the front(left) of the list , and
the sublist of the  items remaining to be sorted that occupy the rest of the list.
Initially the sorted sublist is empty and the unsorted sublist is the entire input
list .The algorithm proceeds by finding the smallest (or largest depending on the
sorting order) element in the unsorted sublist exchanging it with the leftmost
unsorted element (putting in sorted order) and moving the sublist boundaries one
element to the right.

It generally performs worse than the insertion sort though it has performance
advantages over more complicated algorithms especially when auxiliary memory
is limited.
When to Use

Selection sort is good to use for small number of input elements(less than 1000) .
You can see  by running the below algorithm for
(Input)(Space)                           (Time taken)
10 elements           :           Selection sort took   0  milliseconds
100 elements         :           Selection sort took   0  milliseconds
1000 elements       :           Selection sort took   5  milliseconds 
10000 elements     :           Selection sort took   154 milliseconds
100000 elements   :           Selection sort took   13764  milliseconds

So , you can see it is not wise decision to use Selection sort for large number of
elements as other algorithms take much less time .
Big O Notation

In simple words , Big O allows us to say something about how the size of inputs
affect the runtime of a program .This technique can also be applied to other
resources that an algorithm takes up (such as memory)
and we can analyze other bounds than the upper bound such as lower bound on
time or space or expected time or space that an algorithm takes up .

Properties

* It is not a  Stable algorithm i.e does change the relative order of elements with
equal keys

Best , Average,Worst Cases

*  Best Case        :    O(n^2)


* Average Case   :    O(n^2)
* Worst Case      :    O(n^2)
Algorithm:

Program:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

public class SelectionSort


{

private static void swap(int[] a, int i, int j)


{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}

public static int[] selectionSort(int[] list)


{
for (int i = 0; i < list.length - 1; i++)
{
// Find the index of the minimum value
int minPos = i;
for (int j = i + 1; j < list.length; j++)
{
if (list[j] < list[minPos])
{
minPos = j;
}
}
swap(list, minPos, i);
}
return list;
}
public static void main(String args[]) throws Exception
{
String list="";
int i=0,n=0;

SelectionSort s= new SelectionSort();


ArrayList<Integer> arrlist=new ArrayList<Integer>();
System.out.println(" ");
System.out.println(" ");
System.out.println("Please enter the list of elements,one element per line");
System.out.println(" write 'STOP' when list is completed ");
BufferedReader bf=new BufferedReader(new
InputStreamReader(System.in));
while(!(list=bf.readLine()).equalsIgnoreCase("stop"))
{
int intelement=Integer.parseInt(list);
arrlist.add(intelement);

}
int elementlist[] = new int[arrlist.size()];
Iterator<Integer> iter = arrlist.iterator();
for (int j=0;iter.hasNext();j++) {
elementlist[j] = iter.next();
}
elementlist=selectionSort(elementlist);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("Values after Selection Sort : ");
for (int j=0;j<elementlist.length;j++) {
System.out.println(elementlist[j]+" ");
}
}
}
3. Insertion Sort

Sorting is to place elements in increasing or decreasing order.  Insertion sort is a


simple sorting algorithm. In this sorting algorithm, the final sorted array can be
build one at a time .For larger data, when compared to other sorting techniques
like quick sort , heap sort  or merge sort ,it falls short .
When to Use

Insertion sort is good to use for small number of input elements(less than 1000) .
You can see  by running the below algorithm for
(Input)(Space)                           (Time taken)
10 elements           :           Insertion sort took   0  milliseconds
100 elements         :           Insertion sort took   0  milliseconds
1000 elements       :           Insertion sort took   0  milliseconds 
10000 elements     :           Insertion sort took    1 milliseconds
100000 elements   :           Insertion sort took    3 milliseconds

So , you can see it is not wise decision to use Insertion sort for large number of
elements as other algorithms take much less time .
Big O Notation

In simple words , Big O allows us to say something about how the size of inputs
affect the runtime of a program .This technique can also be applied to other
resources that an algorithm takes up (such as memory)
and we can analyze other bounds than the upper bound such as lower bound on
time or space or expected time or space that an algorithm takes up .

Properties

* It is a Stable algorithm i.e does not change the relative order of elements with
equal keys
* Very low overhead
* Online i.e can sort a list as it receives it
Best , Average,Worst Cases

*  Best Case        :    O(n)


* Average Case   :    O(n^2)
* Worst Case      :    O(n^2)

Algorithm:

Program:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

public class InsertionSort


{
public static int[] insertionSort(int[] list)
{
for (int i = 1; i < list.length; i++)
{
int next = list[i];
// find the insertion location while moving all larger element up
int j = i;
while (j > 0 && list[j - 1] > next)
{
list[j] = list[j - 1];
j--;
}
// insert the element
list[j] = next;
}
return list;
}
public static void main(String args[]) throws Exception
{
String list="";
int i=0,n=0;

InsertionSort s= new InsertionSort();


ArrayList<Integer> arrlist=new ArrayList<Integer>();
System.out.println(" ");
System.out.println(" ");
System.out.println("Please enter the list of elements,one element per line");
System.out.println(" write 'STOP' when list is completed ");
BufferedReader bf=new BufferedReader(new
InputStreamReader(System.in));
while(!(list=bf.readLine()).equalsIgnoreCase("stop"))
{
int intelement=Integer.parseInt(list);
arrlist.add(intelement);

}
int elementlist[] = new int[arrlist.size()];
Iterator<Integer> iter = arrlist.iterator();
for (int j=0;iter.hasNext();j++)
{
elementlist[j] = iter.next();
}
elementlist=insertionSort(elementlist);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("Values after Insertion Sort : ");
for (int j=0;j<elementlist.length;j++) {
System.out.println(elementlist[j]+" ");
}
}
}
4. Quick Sort

Quick sort is based on one principle divide and conquer. Quick sort first  divides
the large lists into two sub smaller lists, the low elements and the high
elements .Quick sort can then recursively sort the sublist.
* Choose an element and called it as pivot, in the given list.

* 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 pivot is in its final position. This is called
the partition operation.  

* Recursively apply the above steps to the sublist of the elements with smaller
values and separately the   sublist of elements with greater values.

It is also known as partition exchange sort .Quicksort's sequential and localized


memory references work with a cache .

When to Use

You can see  by running the below algorithm for

(Input)(Space)                           (Time taken)


10 elements           :           Quick sort took   0  milliseconds
100 elements         :           Quick sort took   0  milliseconds
1000 elements       :           Quick sort took   0  milliseconds 
10000 elements     :           Quick sort took   7  milliseconds
100000 elements   :           Quick sort took   38  milliseconds

Big O Notation

In simple words , Big O allows us to say something about how the size of inputs
affect the runtime of a program .This technique can also be applied to other
resources that an algorithm takes up (such as memory)
and we can analyze other bounds than the upper bound such as lower bound on
time or space or expected time or space that an algorithm takes up .

Properties

* It is not a  Stable algorithm .


* It is not adaptive.

Best , Average,Worst Cases

*  Best Case        :    O(n log n)


* Average Case   :    O(n log n)
* Worst Case      :    O(n^2)

Algorithm:

Program:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

public class QuickSort


{
private static void swap(int[] a, int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static void quicksort(int list[], int from, int to)
{
// If the indexes cross, then we've sorted the whole array.
if (from >= to)
{
return;
}

// Choose a pivot value and then partition the array so that every value
// less than the pivot is positioned before the pivot in the array and
// every value greater than the pivot is positioned after the pivot in
// the array.

int pivot = list[from];


int i = from - 1;
int j = to + 1;
while (i < j)
{
// Keep incrementing from the start of the range so long as the
// values are less than the pivot.

i++;
while (list[i] < pivot)
{
i++;
}
// Keep decrementing from the end of the range so long as the values
// are greater than the pivot.

j--;
while (list[j] > pivot)
{
j--;
}
// So long at the indexes have not crossed, swap the pivot with the
// value that was out of place.

if (i < j)
{
swap(list, i, j);
}
}
// Recursively sort the two portions of the array
quicksort(list, from, j);
quicksort(list, j + 1, to);
}

// Helper method that kicks off the recursive quicksort method


public static int[] quicksort(int [] list)
{
quicksort(list, 0, list.length-1);
return list;
}

public static void main(String args[]) throws Exception


{
String list="";
int i=0,n=0;

QuickSort s= new QuickSort();


ArrayList<Integer> arrlist=new ArrayList<Integer>();
System.out.println(" ");
System.out.println(" ");
System.out.println("Please enter the list of elements,one element per line");
System.out.println(" write 'STOP' when list is completed ");
BufferedReader bf=new BufferedReader(new
InputStreamReader(System.in));
while(!(list=bf.readLine()).equalsIgnoreCase("stop"))
{
int intelement=Integer.parseInt(list);
arrlist.add(intelement);
}
int elementlist[] = new int[arrlist.size()];
Iterator<Integer> iter = arrlist.iterator();
for (int j=0;iter.hasNext();j++)
{
elementlist[j] = iter.next();
}
elementlist=quicksort(elementlist);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("Values after Quick Sort : ");
for (int j=0;j<elementlist.length;j++) {
System.out.println(elementlist[j]+" ");
}
}

5. Merger Sort

Merge sort is a divide and conquer algorithm that was invented by John von
Neumann in 1945.

 Merge sort works as follows


*   Divide the unsorted list into n sublists, each containing 1 element (a list of 1
element is considered sorted).
*    Repeatedly merge sublists to produce new sublists until there is only 1 sublist
remaining. This will be the sorted list.

There are naturally two types of merge sort


* Top down approach
* Bottom Up approach

When to Use

Here runtime mostly depends upon the pivotal element you choose .You can see
by running the below algorithm for
(Input)(Space)                           (Time taken)
10 elements           :           Merge sort took   0  milliseconds
100 elements         :           Merge sort took   0  milliseconds
1000 elements       :           Merge sort took   1  milliseconds 
10000 elements     :           Merge sort took   3  milliseconds
100000 elements   :           Merge sort took   97  milliseconds

Big O Notation

In simple words , Big O allows us to say something about how the size of inputs
affect the runtime of a program .This technique can also be applied to other
resources that an algorithm takes up (such as memory)
and we can analyze other bounds than the upper bound such as lower bound on
time or space or expected time or space that an algorithm takes up .

Properties

* It is a Stable algorithm i.e does not change the relative order of elements with
equal keys
* It does not require random access to data

Best , Average,Worst Cases

*  Best Case        :    O(n log n) , or


                                O(n)   
* Average Case   :    O(n log n)
* Worst Case      :    O(n log n)

Algorithm:
Program:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

public class MergeSort {

public static int[] mergeSort(int [] list) {


if (list.length <= 1) {
return list;
}

// Split the array in half


int[] first = new int[list.length / 2];
int[] second = new int[list.length - first.length];
System.arraycopy(list, 0, first, 0, first.length);
System.arraycopy(list, first.length, second, 0, second.length);

// Sort each half


mergeSort(first);
mergeSort(second);

// Merge the halves together, overwriting the original array


merge(first, second, list);
return list;
}

private static void merge(int[] first, int[] second, int [] result) {


// Merge both halves into the result array
// Next element to consider in the first array
int iFirst = 0;
// Next element to consider in the second array
int iSecond = 0;
// Next open position in the result
int j = 0;
// As long as neither iFirst nor iSecond is past the end, move the
// smaller element into the result.
while (iFirst < first.length && iSecond < second.length) {
if (first[iFirst] < second[iSecond]) {
result[j] = first[iFirst];
iFirst++;
} else {
result[j] = second[iSecond];
iSecond++;
}
j++;
}
// copy what's left
System.arraycopy(first, iFirst, result, j, first.length - iFirst);
System.arraycopy(second, iSecond, result, j, second.length - iSecond);
}

public static void main(String args[]) throws Exception


{
String list="";
int i=0,n=0;

MergeSort s= new MergeSort();


ArrayList<Integer> arrlist=new ArrayList<Integer>();
System.out.println(" ");
System.out.println(" ");
System.out.println("Please enter the list of elements,one element per
line");
System.out.println(" write 'STOP' when list is completed ");
BufferedReader bf=new BufferedReader(new
InputStreamReader(System.in));
while(!(list=bf.readLine()).equalsIgnoreCase("stop")){
int intelement=Integer.parseInt(list);
arrlist.add(intelement);
}

int elementlist[] = new int[arrlist.size()];


Iterator<Integer> iter = arrlist.iterator();
for (int j=0;iter.hasNext();j++) {
elementlist[j] = iter.next();
}

elementlist=mergeSort(elementlist);
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("Values after Merge Sort : ");
for (int j=0;j<elementlist.length;j++) {
System.out.println(elementlist[j]+" ");
}
}
}

You might also like