forked from abhpd/hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request abhpd#508 from PRABHU-OFFICIAL/patch-7
Update Selection_Sort.java
- Loading branch information
Showing
1 changed file
with
41 additions
and
34 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,34 +1,41 @@ | ||
package SelectionSort; | ||
|
||
/** | ||
* SelectionSort | ||
*/ | ||
public class SelectionSort { | ||
public static void main(String[] args) { | ||
int[] originalArray = new int[10]; | ||
|
||
for (int i = 0; i < originalArray.length; i++) { | ||
originalArray[i] = (int) (Math.random() * 15); | ||
} | ||
|
||
selectionSort(originalArray); | ||
|
||
for (int i = 0; i < originalArray.length; i++) { | ||
System.out.println(originalArray[i]); | ||
} | ||
} | ||
|
||
public static void selectionSort(int[] array) { | ||
for (int i = 0; i < array.length - 1; i++) { | ||
int k = i; | ||
for(int j = i + 1; j < array.length; j++) { | ||
if (array[j] < array[k]) { | ||
k = j; | ||
} | ||
} | ||
int temp = array[k]; | ||
array[k] = array[i]; | ||
array[i] = temp; | ||
} | ||
} | ||
} | ||
class SelectionSort | ||
{ | ||
void sort(int arr[]) | ||
{ | ||
int n = arr.length; | ||
|
||
|
||
for (int i = 0; i < n-1; i++) | ||
{ | ||
|
||
int min_idx = i; | ||
for (int j = i+1; j < n; j++) | ||
if (arr[j] < arr[min_idx]) | ||
min_idx = j; | ||
|
||
|
||
int temp = arr[min_idx]; | ||
arr[min_idx] = arr[i]; | ||
arr[i] = temp; | ||
} | ||
} | ||
|
||
|
||
void printArray(int arr[]) | ||
{ | ||
int n = arr.length; | ||
for (int i=0; i<n; ++i) | ||
System.out.print(arr[i]+" "); | ||
System.out.println(); | ||
} | ||
|
||
|
||
public static void main(String args[]) | ||
{ | ||
SelectionSort ob = new SelectionSort(); | ||
int arr[] = {64,25,12,22,11}; | ||
ob.sort(arr); | ||
System.out.println("Sorted array"); | ||
ob.printArray(arr); | ||
} | ||
} |