Discuss the various sort algorithms and write a method using

Discuss the various sort algorithms and write a method using either array based lists or linked lists.

Solution

Sorting is a method which is used to order a list of objects or items. There are two types of sorting based upon the memory they are internal sorting and external sorting.We are going to internal sorting.

Bubble sort algorithm: This Bubble sort algorithm which is used for comparing each object or items that are present in list with the items that are present next to it, and rearrange them if necessary.

Method for Bubble sort algorithm using array based list:

void bubbleSort(int arr[])

{

for (int i = (arr.length - 1); i >= 0; i--)

{

for (int j = 1; j i; j++)

{

if ( arr[j-1] > arr[j] )

{

int temp = arr[j-1];

arr[j-1] = arr[j];

arr[j] = temp;

}

}

}

}

Insertion sort algorithm: This insertion sort algorithm which is used to rearrange the unordered list of items.

Insertion sort algorithm method using array based lists:

void insertionSort(int[] arr)

{

for (int i=1; i ‹ arr.length; i++)

{

int index = arr[i]; int j = i;

while (j > 0 && arr[j-1] > index)

{

arr[j] = arr[j-1];

j--;

}

arr[j] = index;

}

}

Selection sort algorithm: This selection sort algorithm which is used for selecting the lowest unsorted item and then rearrange that item with the next item in the position to be occupied.

Selection sort algorithm method using array based lists:

void selectionSort(int[] arr)

{

for (int i = 0; i ‹ arr.length-1; i++)

{

int min = i;

for (int j = i+1; j ‹ arr.length; j++)

if (arr[j] ‹ arr[min]) min = j;

int temp = arr[i];

arr[i] = arr[min];

arr[min] = temp;

}

}

Discuss the various sort algorithms and write a method using either array based lists or linked lists.SolutionSorting is a method which is used to order a list

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site