0% found this document useful (0 votes)
8 views4 pages

555

Uploaded by

Ishita Kolluru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views4 pages

555

Uploaded by

Ishita Kolluru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

public class Selection

void selection(int a[]) /* function to sort an array with selection sort */

int i, j, small;

int n = a.length;

for (i = 0; i < n-1; i++)

small = i; //minimum element in unsorted array

for (j = i+1; j < n; j++)

if (a[j] < a[small])

small = j;

// Swap the minimum element with the first element

int temp = a[small];

a[small] = a[i];

a[i] = temp;

void printArr(int a[]) /* function to print the array */

int i;

int n = a.length;

for (i = 0; i < n; i++)

System.out.print(a[i] + " ");

public static void main(String[] args) {

int a[] = { 91, 49, 4, 19, 10, 21 };

Selection i1 = new Selection();


System.out.println("\nBefore sorting array elements are - ");

i1.printArr(a);

i1.selection(a);

System.out.println("\nAfter sorting array elements are - ");

i1.printArr(a);

System.out.println();

INSERTION SORT

public class Insert

void insert(int a[]) /* function to sort an aay with insertion sort */

int i, j, temp;

int n = a.length;

for (i = 1; i < n; i++) {

temp = a[i];

j = i - 1;
while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one position ahead
from their current position*/

a[j+1] = a[j];

j = j-1;

a[j+1] = temp;

void printArr(int a[]) /* function to print the array */

int i;

int n = a.length;

for (i = 0; i < n; i++)

System.out.print(a[i] + " ");

public static void main(String[] args) {

int a[] = { 92, 50, 5, 20, 11, 22 };

Insert i1 = new Insert();

System.out.println("\nBefore sorting array elements are - ");

i1.printArr(a);

i1.insert(a);

System.out.println("\n\nAfter sorting array elements are - ");

i1.printArr(a);

System.out.println();

}
S

You might also like