Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

selection_sort.java: Creating Selection Sort Algorithm in Java #516

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ This repository contains examples of various algorithms written on different pro
| [Heap Sort](https://en.wikipedia.org/wiki/Heapsort) | | | | [:octocat:](heap_sort/python) |
| [Maximum Subarray Problem](https://en.wikipedia.org/wiki/Maximum_subarray_problem) | | | | [:octocat:](/maximum_subarray/Python)|
| [Knapsack Problem](https://en.wikipedia.org/wiki/Knapsack_problem) | | | | [:octocat:](knapsack_problem/Python)|
| [Selecton Sort](https://en.wikipedia.org/wiki/Selection_sort) | [:octocat:](selection_sort/C) | | | |
| [Selecton Sort](https://en.wikipedia.org/wiki/Selection_sort) | [:octocat:](selection_sort/C) | | [:octocat:](selection_sort/Java) | |


## Implemented Data Structures
Expand Down
40 changes: 40 additions & 0 deletions selection_sort/Java/selection_sort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
public class selection_sort {

//Main function. Instanciates the unsorted array and calls mergesort.
public static void main(String args[]) {

//Example Array
int example[] = {9, 5, 4, 6, 1, 2, 3, 1, 2, 3};
selection_sort(example);
print_sorted_array(example);
}

// Method to take minimum and switch it with each successive place in the array through the penultimate index
static void selection_sort(int array[]) {
int len = array.length;
for (int i = 0; i < len - 1; i++) {
int min = i;
// Checks for minimum through entire array
for (int j = i + 1; j < len; ++j) {
if (array[j] < array[min])
min = j;
}
// temp is needed in order to be able to switch the two values.
int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}

//Method taken from bubble_sort.java
//Method to print an array
public static void print_sorted_array(int arr[]) {

//storing the length of an array using the .length function in Java
int n = arr.length;
//For loop that iterates over each element of the array and then prints it.
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
}