You are on page 1of 23

Shell Sort:

Shellsort, also known as Shell sort or Shell's method, is an in-place comparison sort. This technique is also called sorting with diminishing increments It generalizes an exchanging sort, such as insertion or bubble sort, by starting the comparison and exchange of elements with elements that are far apart before finishing with neighbouring elements. Starting with far apart elements can move some outof-place elements into position faster than a simple nearest neighbour exchange. Donald Shell published the first version of this sort in 1959. The running time of Shell sort is heavily dependent on the gap sequence it uses. For many practical variants, determining their time complexity remains an open problem. Algorithm: 1.Establish an array a[] of n elements. 2.set increment inc to n/2. 3.divide the array into inc sub arrays with inc as the increment size. 4.sort these sub arrays individually. 5.Reduce inc to inc/2. 6.Repeat steps 3 through 5 tll inc is equal to 1. 7.Return the sorted array.

C++ implementation of Shell Sort:


#include<iostream>
u s i n g n a m e s p a c e std; i n t shell (i n t x[], i n t n) {i n t i, j, k, no, inc; f o r (inc = n/2; inc >=1; inc/=2) f o r (k = 0; k < inc ; k++) {/* This is insertion sort */ f o r (i = k; i < n-inc; i+=inc) { no = x[i+inc]; f o r (j = i; j >= k; j-=inc) i f (no > x[j]) b reak ; e l s e x[j+inc] = x[j]; x[j+inc] = no; } /* insertion sort ends */ } r e t u r n 0; } i n t main() { i n t n,a[100]; cout<<"enter no of elements:"; cin>>n; cout<<"enter elements:"; f o r (i n t i=0;i<n;i++) { cin>>a[i]; } shell(a,n); cout<<"the sorted array is:"; f o r (i n t i=0;i<n;i++) { cout<<a[i] << ; } r e t u r n 0; }

Output:

Java Implementation :
import java. util.Scanner; p u b l i c c l a s s sort { p u b l i c s t a t i c v o i d shell (i n t x[], i n t n) {i n t i, j, k, no, inc; f o r (inc = n/2; inc >=1; inc/=2) f o r (k = 0; k < inc ; k++) { f o r (i = k; i < n-inc; i+=inc) { no = x[i+inc]; f o r (j = i; j >= k; j-=inc) i f (no > x[j]) b reak ; e l s e x[j+inc] = x[j]; x[j+inc] = no; } } } p u b l i c s t a t i c v o i d main(String[] args){ i n t n; i n t a[] = n e w i n t [100]; System.out.println("enter no of elements:"); Scanner sc = n e w Scanner(System.in); n = sc.nextInt(); System.out.println("enter elements:"); f o r (i n t i=0;i<n;i++) { a[i] = sc.nextInt(); } shell(a,n); System.out.print("the sorted array is:"); f o r (i n t i=0;i<n;i++) { System.out.print(a[i] + " "); } } }

Performance of algorithm: The analysis of shell sort requires a lot of mathematical analysis.Eventhough at the core of the shell sort ,we have insertion sort,the analysis varies from that of insertion sort,The efficiency of the sorts depends in the values of the diminishing increments,They should have prime numbers so as to effect proper mixing ofelements.If that is achieved for the last pass,which is like implementing classical insertion sort,minimum numbers of shifting are required.mathematical analysis shows shell sort to be more efficient than classical insertion sort with O(n1.5).

Merge Sort: A Merge sort (also commonly spelled mergesort) is an O(n log n) comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945. Algorithm: 1.Establish an array a[] of n elements. 2.Consider size equal to unity. 3.Subdivide the array in sub arrays of size n. 4.Merge the sub arrays in pairs of 2 such that they remain sorted. 5.Double the size. 6. repeat steps 3 to 5 till size exceeds array size. 7. return sorted array. C++ Implementation .
#include<iostream> u s i n g n a m e s p a c e std; i n t mergesort(i n t x[], i n t lb, i n t ub) { i n t merge(i n t [], i n t , i n t , i n t ); i n t mid; i f (lb < ub) {mid = (lb + ub) / 2; mergesort(x, lb, mid); mergesort(x, mid+1, ub); merge(x, lb, mid, ub); } r e t u r n 0; } i n t merge(i n t x[], i n t lb1, i n t ub1, i n t ub2) { i n t temp[10], i = lb1, j = ub1 + 1, k = 0; w h i l e (i <= ub1 && j <= ub2) i f (x[i] < x[j]) temp[k++] = x[i++]; e l s e temp[k++] = x[j++]; w h i l e (i <= ub1) temp[k++] = x[i++]; w h i l e (j <= ub2) temp[k++] = x[j++]; f o r (i = lb1, j = 0; i <= ub2; i++, j++) x[i] = temp[j]; r e t u r n 0; } i n t main() { i n t n,a[100]; cout<<"enter no of elements:"; cin>>n; cout<<"enter elements:"; f o r (i n t i=0;i<n;i++) { cin>>a[i]; } mergesort(a,0,n); cout<<"the sorted array is:"; f o r (i n t i=0;i<n;i++) { cout<<a[i] << ; } r e t u r n 0; }

Output:

Java Implementation:
import java. util.Scanner;p u b l i c c l a s s sort { p u b l i c s t a t i c v o i d mergesort(i n t x[], i n t lb, i n t ub){ i n t mid; i f (lb < ub) {mid = (lb + ub) / 2; mergesort(x, lb, mid); mergesort(x, mid+1, ub); merge(x, lb, mid, ub); } } p r i v a t e s t a t i c v o i d merge(i n t x[], i n t lb1, i n t ub1, i n t ub2){ i n t temp[], i = lb1, j = ub1 + 1, k = 0; temp = n e w i n t [10]; w h i l e (i <= ub1 && j <= ub2) i f (x[i] < x[j]) temp[k++] = x[i++]; e l s e temp[k++] = x[j++]; w h i l e (i <= ub1) temp[k++] = x[i++]; w h i l e (j <= ub2) temp[k++] = x[j++]; f o r (i = lb1, j = 0; i <= ub2; i++, j++) x[i] = temp[j]; } p u b l i c s t a t i c v o i d main(String[] args){ i n t n; i n t a[] = n e w i n t [100]; System.out.println("enter no of elements:"); Scanner sc = n e w Scanner(System.in); n = sc.nextInt(); System.out.println("enter elements:"); f o r (i n t i=0;i<n;i++){ a[i] = sc.nextInt(); } mergesort(a,0,n); System.out.print("the sorted array is:"); f o r (i n t i=0;i<n;i++){ System.out.print(a[i] + " "); } } }

Output:

Performance of algorithm: Suppose that the file size i s of the power 2,say n=2^m,so that m=logn to the base 2.In Mer ge sort it i s obvious that no longer than m passes will be required. During each pass, maximum n comparisons will be required. This indicates that maximum m*n comparisons will be required which implies that nlogn.Thus merge sort is O(nlogn). You can observe the effective change in runtime (exeution time).

Quick Sort: Quicksort, or partition-exchange sort, is a sorting algorithm developed by Tony Hoare that, on average, makes O(n log n) comparisons to sort n items. In the worst case, it makes O(n2) comparisons, though this behavior is rare. Quicksort is often faster in practice than other O( n log n) algorithms. Additionally, quicksort's sequential and localized memory references work well with a cache. Quicksort is a comparison sort and, in efficient implementations, is not a stable sort. Quicksort can be implemented with an in-place partitioning algorithm, so the entire sort can be done with only O(log n) additional space used by the stack during the recursion. Algorithm: 1. Partition the current array into two sub arrays. 2. Invoke quicksort to left sub array. 3. Invoke quicksort to right sub array. C++ Implementation:
#include<iostream> u s i n g n a m e s p a c e std; i n t partition (i n t x[], i n t lb, i n t ub) {i n t pos = lb, i, temp; f o r (i = lb+1; i <= ub; i++) i f (x[i] < x[lb]) {pos++; temp = x[pos]; x[pos] = x[i]; x[i] = temp; } temp = x[pos]; x[pos] = x[lb]; x[lb] = temp; r e t u r n pos; } v o i d quicksort(i n t x[], i n t lb, i n t ub) {i n t partition(i n t x[], i n t , i n t ); i n t p; i f (lb < ub) {p = partition(x, lb, ub); quicksort(x, lb, p-1); quicksort(x, p+1, ub); } } i n t main() { i n t n,a[100]; cout<<"enter no of elements:"; cin>>n; cout<<"enter 3 digit elements:"; f o r (i n t i=0;i<n;i++) { cin>>a[i]; } quicksort(a,0,n); cout<<"the sorted array is:"; f o r (i n t i=0;i<n;i++) { cout<<a[i]; } r e t u r n 0; }

Output

Java implementation
import java. util.Scanner; p u b l i c c l a s s sort { p r i v a t e s t a t i c i n t partition (i n t x[], i n t lb, i n t ub) {i n t pos = lb, i, temp; f o r (i = lb+1; i <= ub; i++) i f (x[i] < x[lb]) {pos++; temp = x[pos]; x[pos] = x[i]; x[i] = temp; } temp = x[pos]; x[pos] = x[lb]; x[lb] = temp; r e t u r n pos; } p u b l i c s t a t i c v o i d quicksort(i n t x[], i n t lb, i n t ub) { i n t p; i f (lb < ub) {p = partition(x, lb, ub); quicksort(x, lb, p-1); quicksort(x, p+1, ub); } } p u b l i c s t a t i c v o i d main(String[] args){ i n t n; i n t a[] = n e w i n t [100]; System.out.println("enter no of elements:"); Scanner sc = n e w Scanner(System.in); n = sc.nextInt(); System.out.println("enter elements:"); f o r (i n t i=0;i<n;i++) { a[i] = sc.nextInt(); } quicksort(a,0,n); System.out.print("the sorted array is:"); f o r (i n t i=0;i<n;i++) { System.out.print(a[i] + " "); } } }

Output:

Performance of algorithm:
Quicksort takes O(n log n) time on average, when the input is a random permutation. Why? For a start, it is not hard to see that the partition operation takes O( n) time.In the most unbalanced case, each time we perform a partition we divide the list into two sublists of size 0 and n-1 (for example, if all elements of the array are equal). This means each recursive call processes a list of size one less than the previous list. Consequently, we can make n-1 nested calls before we reach a list of size 1. This means that the calltree is a linear chain of n-1 nested calls. The ith call does O(n-1) work to do the partition, and O(n^2) , so in that case Quicksort takes O(n^2) time.That is the worst case: given knowledge of which comparisons are performed by the sort, there are adaptive algorithms that are effective at generating worst-case input for quicksort on-the-fly, regardless of the pivot selection strategy

Radix Sort:
radix sort is a non-comparative integer sortingalgorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value. A positionalnotation is required, but because integers can represent strings of characters (e.g., names or dates) and specially formatted floating point numbers, radix sort is not limited to integers. Radix sort dates back as far as 1887 to the work of Herman Hollerith on tabulatingmachines. Most digital computers internally represent all of their data as electronic representations of binary numbers, so processing the digits of integer representations by groups of binary digit representations is most convenient. Two classifications of radix sorts areleastsignificantdigit (LSD) radix sorts and mostsignificantdigit (MSD) radix sorts. LSD radix sorts process the integer representations starting from the least digit and move towards the most significant digit. MSD radix sorts work the other way around. The integer representations that are processed by sorting algorithms are often called "keys", which can exist all by themselves or be associated with other data. LSD radix sorts typically use the following sorting order: short keys come before longer keys, and keys of the same length are sorted lexicographically. This coincides with the normal order of integer representations, such as the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. MSD radix sorts use lexicographic order, which is suitable for sorting strings, such as words, or fixed-length integer representations. A sequence such as "b, c, d, e, f, g, h, i, j, ba" would be lexicographically sorted as "b, ba, c, d, e, f, g, h, i, j". If lexicographic ordering is used to sort variable-length integer representations, then the representations of the numbers from 1 to 10 would be output as 1, 10, 2, 3, 4, 5, 6, 7, 8, 9, as if the shorter keys were left-justified and padded on the right with blank characters to make the shorter keys as long as the longest key for the purpose of determining sorted order. Algorithm: 1. Establish array a[] of n elements. 2. Call bucket sort repeatedly on least to most significant digit of each element as the key. 3. Return the stored array.

C++ Implementation:
#include<iostream> #include<math> u s i n g n a m e s p a c e std; t y p e d e f i n t qelement; t y p e d e f s t r u c t node { qelement data; s t r u c t node *next; } node; ty p ed ef s t ru ct { node *first, *last;}qtype; v o i d initialise(qtype *qptr) {qptr->first = NULL;} i n t addq(qtype *qptr, qelement no) {node *p; p = (node*) malloc (s i z e o f (node)); i f (p==NULL) r e t u r n 0; p->data = no; p->next = NULL; i f (qptr->first == NULL) qptr->first = p; e l s e qptr->last->next = p; qptr->last = p; r e t u r n 1; } i n t delq (qtype *qptr, qelement *noptr) {node *p = qptr->first; i f (p== NULL)r e t u r n 0; *noptr = p->data; qptr->first = p->next; free (p); r e t u r n 1; }

i n t radix (i n t x[], i n t n, i n t digs) {qtype q[10];

i n t i, j, k, no; f o r (k = 1; k <= digs; k++) {f o r (i = 0; i < 10; i++) initialise(&q[i]); f o r (i = 0; i < n; i++) { i n t dig; dig = x[i]/ (i n t )(pow(10,k-1)) % 10; addq(&q[dig], x[i]); } f o r (i = 0, j = 0; i < 10; i++) { w h i l e (delq(&q[i], &no)) x[j++] = no; } } retu rn ; } i n t main() { i n t n,a[100]; cout<<"enter no of elements:"; cin>>n; cout<<"enter 3 digit elements:"; f o r (i n t i=0;i<n;i++) { cin>>a[i]; } radix(a,n,3); cout<<"the sorted array is:"; f o r (i n t i=0;i<n;i++) { cout<<a[i]; } r e t u r n 0; }

Output :

Java Implementation:
import java. util.ArrayList; i m p o r t java.util.LinkedList; i m p o r t java.util.List; i m p o r t java.util.Queue; p u b l i c c l a s s RadixSort.java { p r i v a t e s t a t i c int[] unsorted = n u l l ; p r i v a t e s t a t i c L i s t <Queue<I n t e g e r >> buckets = n e w ArrayList<Queue<I n t e g e r >>(); p r i v a t e RadixSort() { } p u b l i c s t a t i c int[] sort(int[] unsorted) { RadixSort.unsorted = unsorted; f o r (int i=0; i<10; i++) { Queue<I n t e g e r > bucket = n e w LinkedList<I n t e g e r >(); buckets.add(i, bucket); } int numberOfDigits = findMaxNumberOfDigits(); f o r (int n=0; n<numberOfDigits; n++) {

f o r (int i=0; i<RadixSort.unsorted.length; i++) { int e = RadixSort.unsorted[i]; int digit = getDigitAt(e,n); buckets.get(digit).add(e); } int i=0; f o r (Queue<I n t e g e r > bucket : buckets) { f o r (int integer : bucket) { RadixSort.unsorted[i++] = integer; } bucket.clear(); } } r e t u r n RadixSort.unsorted; } p r i v a t e s t a t i c int getDigitAt(int integer, int pos) { int div = (int)M a t h .floor(M a t h .pow(10,pos)); int mod = (int)M a t h .floor(M a t h .pow(10,pos+1)); int i = integer % mod; i f (div>0) i /= div; r e t u r n i; } p r i v a t e s t a t i c int findMaxNumberOfDigits() { int max = I n t e g e r .MIN_VALUE; f o r (int e : unsorted) { S t r i n g str = S t r i n g .valueOf(e); int length = str.length(); i f (length>max) max = length; } r e t u r n max; } }

Output:

Performance of Algorithm: The logarithm takes O(n) time per bucket sort. There are logk=O(logn) bucket sorts.So the total time is O(nlogk),where k is the largest key in the data.

Heap Sort:
Heapsort is a comparison-based sorting algorithm to create a sorted array (or list), and is part of the selection sort family. Although somewhat slower in practice on most machines than a wellimplemented quicksort, it has the advantage of a more favourable worst-case O(n log n) runtime. Heapsort is an in-place algorithm, but it is not a stable sort. It was invented by J. W. J. Williams in 1964. The heapsort algorithm can be divided into two parts. In the first step, a heap is built out of the data. In the second step, a sorted array is created by repeatedly removing the largest element from the heap, and inserting it into the array. The heap is reconstructed after each removal. Once all objects have been removed from the heap, we have a sorted array. The direction of the sorted elements can be varied by choosing a minheap or max-heap in step one. Heapsort can be performed in place. The array can be split into two parts, the sorted array and the heap. The storage of heaps as arrays is diagrammed here. The heap's invariant is preserved after each extraction, so the only cost is that of extraction. Algorithm: 1. Establish the array a[] of n elements. 2. With the elements of the array create an in place max heap. 3. Swap the first element with the last element of the array. 4. Without considering the last element ,adjust the elements of the array so as to again represent max heap. 5. Repeat steps 3 and 4 for subsequent element. 6. Return the sorted array.

C++ Implementation
#include<iostream> u s i n g n a m e s p a c e std; v o i d swap(i n t *a, i n t *b) { i n t temp = *a; *a = *b; *b = temp; } v o i d heapup(i n t x[], i n t root, i n t bottom) { i n t parent, temp; i f (bottom > root) { parent = (bottom -1) / 2; i f (x[parent] < x[bottom]) {swap(&x[parent], &x[bottom]); heapup(x, root, parent); } } } v o i d heapdown(i n t x[], i n t root, i n t bottom) {i n t lchild = 2*root+1, rchild = 2*root+2, maxchild, temp; i f (lchild <= bottom) {i f (lchild == bottom) maxchild = lchild; e l s e i f (x[lchild] > x[rchild]) maxchild = lchild; e l s e maxchild = rchild; i f (x[root] < x[maxchild]) {swap(&x[root], &x[maxchild]); heapdown(x, maxchild, bottom); } } } v o i d heapsort(i n t x[], i n t n) {i n t i, temp; f o r (i = 0; i < n-1; i++) heapup(x, 0, i+1); f o r (i = n-1; i > 0; i){ swap(&x[0], &x[i]); heapdown(x, 0, i-1); } } i n t main()

i n t n,a[100]; cout<<"enter no of elements:"; cin>>n; cout<<"enter 3 digit elements:"; f o r (i n t i=0;i<n;i++){ cin>>a[i]; } heapsort(a,n); cout<<"the sorted array is:"; f o r (i n t i=0;i<n;i++){ cout<<a[i]; } r e t u r n 0; }

Output:

Java Implementation
import java. util.Scanner; p u b l i c c l a s s sort { p r i v a t e s t a t i c void swap(int a, int b) { int temp = a; a = b; b = temp; } p r i v a t e s t a t i c void heapup(int x[], int root, int bottom) { int parent; i f (bottom > root) { parent = (bottom -1) / 2; i f (x[parent] < x[bottom]) {swap(x[parent], x[bottom]); heapup(x, root, parent); } } } p r i v a t e s t a t i c void heapdown(int x[], int root, int bottom) {int lchild = 2*root+1, rchild = 2*root+2, maxchild; i f (lchild <= bottom) {i f (lchild == bottom) maxchild = lchild; e l s e i f (x[lchild] > x[rchild]) maxchild = lchild; e l s e maxchild = rchild; i f (x[root] < x[maxchild]) {swap(x[root], x[maxchild]); heapdown(x, maxchild, bottom); } } } p u b l i c s t a t i c void heapsort(int x[], int n) {int i;

f o r (i = 0; i < n-1; i++) heapup(x, 0, i+1); f o r (i = n-1; i > 0; i--) {swap(x[0], x[i]); heapdown(x, 0, i-1); } } p u b l i c s t a t i c void main(S t r i n g [] args){ int n; int a[] = n e w int[100]; S y s t e m .out.println("enter no of elements:"); Scanner sc = n e w Scanner(S y s t e m .in); n = sc.nextInt(); S y s t e m .out.println("enter elements:"); f o r (int i=0;i<n;i++) { a[i] = sc.nextInt(); } heapsort(a,n); S y s t e m .out.print("the sorted array is:"); f o r (int i=0;i<n;i++) { S y s t e m .out.print(a[i] + " "); } } }

Output:

Performance of algorithm: , another very efficient general purpose nearly-in-place comparisonHeapsort primarily competes with quicksort based sort algorithm. Quicksort is typically somewhat faster due to some factors, but the worst-case running time for quicksort is O(n2), which is unacceptable for large data sets and can be deliberately triggered given enough knowledge of the implementation, creating a security risk. See quicksort for a detailed discussion of this problem and possible solutions. Thus, because of the O(n log n) upper bound on heapsort's running time and constant upper bound on its auxiliary storage, embedded systems with real-time constraints or systems concerned with security often use heapsort. Heapsort also competes with mergesort, which has the same time bounds. Merge sort requires (n) auxiliary space, but heapsort requires only a constant amount. Heapsort typically runs faster in practice on machines with small or slow datacaches. On the other hand, merge sort has several advantages over heapsort:

Bucket Sort Bucket sort, or bin sort, is a sorting algorithm that works by partitioning an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is adistribution sort, and is a cousin of radix sort in the most to least significant digit flavour. Bucket sort is a generalization of pigeonhole sort. Since bucket sort is not a comparison sort, the (n log n) lower bound is inapplicable. The computational complexity estimates involve the number of buckets. Algorithm:

1. 2. 3. 4.

Set up an array of initially empty "buckets". Scatter: Go over the original array, putting each object in its bucket. Sort each non-empty bucket. Gather: Visit the buckets in order and put all elements back into the original array.

C++ Implementation:
#include<iostream> u s i n g n a m e s p a c e std; i n t bucket(i n t n,i n t x[]){ i n t i,j,count[100]={0}; f o r (i=0;i<n;i++){ count[x[i]]=count[x[i]]+1; }j=0; f o r (i=0;i<=n;i++) { i f (count[i]!=0){ x[j]=i; j++; } } r e t u r n 0; } i n t main() { i n t n,a[100]; cout<<"enter no of elements:"; cin>>n; cout<<"enter elements:"; f o r (i n t i=0;i<n;i++){ cin>>a[i]; } bucket(n,a); cout<<"the sorted array is:"; f o r (i n t i=0;i<n;i++){ cout<<a[i]; } r e t u r n 0;

}
Output:

Java implementation:
import java. util. Scanner; p u b l i c c l a s s sort { p u b l i c s t a t i c int bucket(int n,int x[]){ int i,j,count[]; count = n e w int[100]; f o r (i=0;i<n;i++){ count[x[i]]=count[x[i]]+1; }j=0; f o r (i=0;i<=n;i++) { i f (count[i]!=0){ x[j]=i; j++; } } r e t u r n 0; } p u b l i c s t a t i c void main(S t r i n g [] args){ int n; int a[] = n e w int[100]; S y s t e m .out.println("enter no of elements:"); Scanner sc = n e w Scanner(S y s t e m .in); n = sc.nextInt(); S y s t e m .out.println("enter elements:"); f o r (int i=0;i<n;i++) { a[i] = sc.nextInt(); } bucket(n,a); S y s t e m .out.print("the sorted array is:"); f o r (int i=0;i<n;i++) { S y s t e m .out.print(a[i] + " "); } } }

Output:

Perf ormance of algorithm: Bucket sort can be seen as a generalization of coun s ze 1 ti ng so rt; i n f act , if each bucke t has i t hen bucke t so rt degene r a t est o counting sort. The variable bucket size of bucket sort allows it to use O(n) memory instead of O(M) memory, where M is the number of distinct values; in exchange, it gives up counting sort's O(n + M) worst-case behavior. Bucket sort with two buckets is effectively a version of quicksort where the pivot value is always selected to be the middle value of the value range. While this choice is effective for uniformly distributed inputs, other means of choosing the pivot in quicksort such as randomly selected pivots make it more resistant to clustering in the input distribution.

Insertion Sort:

Algorithm
for i 1 to i length(A) { valueToInsert A[i] holePos i w h i l e holePos > 0 and valueToInsert < A[holePos - 1] { A[holePos] A[holePos - 1] holePos holePos - 1 } A[holePos] valueToInsert }

C++ Implementation
#include<iostream> using namespace std; int a[100]; int max; void sort(int n){ max=n; int temp; f o r (int i=0;i<max;i++){ f o r (int j=i;j>0;j--){ i f (a[j]<=a[j-1]){ temp=a[j-1]; a[j-1]=a[j]; a[j]=temp; } el s e b reak ; } } void print(){ f o r (int i=0;i<max;i++) cout<<""<<a[i]; } int main(){ int n; cout<<"enter the maximum no of elements in array:"; cin>> n; cout<<"enter arrray elements"; f o r (int j=0;j<n;j++) cin>>a[j]; sort(n); print(); r e t u r n 0; }

Output

Java Implementation
i m p o r t java.util.* ; p u b l i c c l a s s insertion { p u b l i c int a[]=n e w int[100]; int max; p u b l i c void sort(int n){ max=n; int temp; f o r (int i=0;i<max;i++){ f o r (int j=i;j>0;j--){ i f (a[j]<=a[j-1]){ temp=a[j-1]; a[j-1]=a[j]; a[j]=temp; } el s e b reak ; } } } p u b l i c void print() {f o r (int i=0;i<max;i++) S y s t e m .out.print(""+a[i]); } p u b l i c s t a t i c void main(S t r i n g []args){ Scanner sc=n e w Scanner(S y s t e m .in); insertion i=n e w insertion(); S y s t e m .out.println("enter the maximum no of elements in array:"); int n=sc.nextInt(); S y s t e m .out.println("enter arrray elements"); f o r (int j=0;j<n;j++){ i.a[j]=sc.nextInt(); } i.sort(n); i.print(); } }

Output

Performance of algorithm From the program, we can see that we have one for loop and one while loop. So, the time complexity will be O(n^2)

Bubble Sort:

Algorithm
1. 2.

Read the array of n elements repeat the following n-1 times


1. 2. 3.

for all adjacent pairs of elements in the unsorted part of the array if current is greter than the next then swap

C++ Implementation
#include <iostream> #include <cstdio> using namespace std; int a[100]; int max; void sort(int n){ max=n; int temp; f o r (int i=0;i<max;i++){ f o r (int j=1;j<max;j++){ i f (a[j-1]>=a[j]){ temp=a[j-1]; a[j-1]=a[j]; a[j]=temp; } } } } void print(){ f o r (int i=0;i<max;i++){ cout<<" "<<a[i]; } } int main(){ int n; cout<<"Enter the maximum no of elements in array: "; cin>> n; cout<<"Enter arrray elements: "; f o r (int j=0;j<n;j++){ cin>>a[j]; } sort(n); print(); r e t u r n 0; }

Output

Java Implementation
import java. util.Scanner; p u b l i c c l a s s bubble { p u b l i c int a[]=n e w int[100]; int max; p u b l i c void sort(int n){ max=n; int temp; f o r (int i=0;i<max;i++) { f o r (int j=1;j<max;j++){ i f (a[j-1]>=a[j]) {temp=a[j-1]; a[j-1]=a[j]; a[j]=temp; } } } } p u b l i c void print() {f o r (int i=0;i<max;i++) S y s t e m .out.print(""+a[i]); } p u b l i c s t a t i c void main(S t r i n g []args){ Scanner sc=n e w Scanner(S y s t e m .in); bubble i=n e w bubble(); S y s t e m .out.println("enter the maximum no of elements in array:"); int n=sc.nextInt(); S y s t e m .out.println("enter arrray elements"); f o r (int j=0;j<n;j++){ i.a[j]=sc.nextInt(); } i.sort(n); i.print(); } }

Output

Performance of algorithm From the program, we can see that we have two for loop. So, the time complexity will be O(n^2)

Selection Sort:

Algorithm
int i,j; int iMin; for (j = 0; j < n-1; j++) { iMin = j; for ( i = j+1; i < n; i++) { if (a[i] < a[iMin]) { iMin = i; } } if ( iMin != j ) { swap(a[j], a[iMin]); } }

C++ Implementation

#include<iostream> using namespace std; int a[100]; int max; void sort(int n){ max=n; int temp,min,k=0; f o r (int i=0;i<max;i++){ min=a[i]; f o r (int j=i;j<max;j++){ i f (min>=a[j]) {min=a[j]; k=j; } } a[k]=a[i]; a[i]=min; } } void print(){ f o r (int i=0;i<max;i++) cout<<" "<<a[i]; } int main(){ int n; cout<<"Enter the maximum no of elements in array: "; cin>> n; cout<<"Enter arrray elements: "; f o r (int j=0;j<n;j++) cin>>a[j]; sort(n); print(); r e t u r n 0; }

Output

Java Implementation
import java. util.Scanner; p u b l i c c l a s s selection { p u b l i c int a[]=n e w int[100]; int max; p u b l i c void sort(int n){ max=n; int temp,min,k=0; f o r (int i=0;i<max;i++){ min=a[i]; f o r (int j=i;j<max;j++){ i f (min>=a[j]) {min=a[j]; k=j; } } a[k]=a[i]; a[i]=min; } } p u b l i c void print() {f o r (int i=0;i<max;i++) S y s t e m .out.print(""+a[i]); } p u b l i c s t a t i c void main(S t r i n g []args){ Scanner sc=n e w Scanner(S y s t e m .in); selection i=n e w selection(); S y s t e m .out.println("enter the maximum no of elements in array:"); int n=sc.nextInt(); S y s t e m .out.println("enter arrray elements"); f o r (int j=0;j<n;j++){ i.a[j]=sc.nextInt(); } i.sort(n); i.print(); } }

Output

Performance of algorithm From the program, we can see that we have two for loop. So, the time complexity will be O(n^2)

You might also like