What is Linear Sort in Java ?

  • One of the simplest Sorting techniques is a linear sort.
  • Linear sort is the selection of an element and keeping it in sorted order.
  • In linear sort, the strategy is to find the smallest number in the array and exchange it with the value in first position of array.
  • Now, find the second smallest element in the remainder of array and exchange it with a value in the second position, carry on till you have reached the end of array.
  • Now all the elements have been sorted in ascending order.
 Linear Sorting

Sample Code

// Java program for implementation of Selection Sort 
class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;

// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first
// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}

// Prints the array
void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}

// Driver code to test above
public static void main(String args[])
{
SelectionSort ob = new SelectionSort();
int arr[] = {27,28,45,68,32};
ob.sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}

Output

Sorted array:
27 28 32 45 68 

Categorized in:

Java

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Share Article:

Leave a Reply

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock