Implementation of selection sort in Java - java

I think I have done the selection sort but I am not sure. Is this really an implementation of selection sort?
static void selectionSort()
{
int min = Integer.MIN_VALUE;
int n = 0;
for(int I=0; I<arraySize; I++)
{
min = dataArray[I];
for(int j=I; j<n; j++)
{
if(dataArray[min]<dataArray[j])
{
min = j;
if(dataArray[min] < dataArray[I])
{
int temp = dataArray[I];
dataArray[I] = dataArray[min];
dataArray[min] = temp;
}
}
}
}
}

I'm not sure I understand how your algorithm works at all. Specifically, you do
min = dataArray[i];
and then later
dataArray[min]<dataArray[j]
i.e. you treat min both as a value in the array, and an index.
Selection sort works as follows:
Find the minimum value in the list
Swap it with the value in the first position
Repeat the steps above for the remainder of the list
(source)
The changes required for your code to accurately implement selection sort would be the following:
Change the inner loop to just find the index of the smallest element. Call it minIndex for instance.
Do the swapping after the inner loop. i.e., swap element at index I with minIndex.
Oh, and as DonCallisto points out in the comments, you may want to do n = dataArray.length instead of n = 0 :-)

public class SelectionSort {
/**
* #Author Chandrasekhara Kota
*/
public static void main(String[] args) {
int arr[]={9,1,8,5,7,-1,6,0,2,2718};
int sortedArr[]=selectionSort(arr);
for (int i = 0; i <sortedArr.length; i++)
{
System.out.println(sortedArr[i]);
}
}
private static int[] selectionSort(int[] arr) {
int minIndex, tmp;
int n = arr.length;
for (int i = 0; i < n - 1; i++)
{
minIndex = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[minIndex])
minIndex = j;
if (minIndex != i) {
tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
return arr;
}
}

Here is a selection sort implementation in java -
public class SelectionSort {
static int intArray[] = { 10, 5, 100, 1, 10000 };
public static void doSort() {
for (int outer = 0; outer < intArray.length; outer++) {
int minPosition=outer;
for(int inner=outer;inner<intArray.length;inner++){
if(intArray[inner]<intArray[minPosition]){
minPosition=inner;
}
}
int temp=intArray[minPosition];
intArray[minPosition]=intArray[outer];
intArray[outer]=temp;
}
}
public static void printArray() {
for (int i = 0; i < intArray.length; i++) {
System.out.print(" " + intArray[i]);
}
}
public static void main(String args[]) {
System.out.print("Array Before Sorting->");
printArray();
doSort();
System.out.print("\nArray After Sorting ->");
printArray();
}
}
The above code is picked from - http://www.javabrahman.com/algorithms-in-java/selection-sort-in-java/. This link has detailed explanation on the working of the above code just in case you need the same.

Related

how to reuse elements of an array out of its for loop?

I was trying to create a code that rearranges given elements in an array -by the user- in ascending order, and I have done that, but the program requires
printing the given elements after sorting them firstly, then printing them before sorting.
I have no problem with printing the elements after sorting
the problem is with printing them before sorting
how to re-use ar[S] = in.nextInt() the given elements by the user out of its for loop
import java.util.*;
public class SortingnumbersANDswapping {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int swap;
int ar[] = new int[3]; //{8,10,5}
for (int S = 0; S < ar.length; S++) {
ar[S] = in.nextInt(); //this for loop is used to store numbers in the array
}
for (int i = 0; i < ar.length; i++) {
/* this nested for loop is used to compare the first element with the second one in the array
or the second element with the third.
*/
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] > ar[j]) { //8>10-->F , 8>5 -->T , {5,10,8} the new arrangment we are going to use
swap = ar[i]; // 10>8-->T {5,8,10}
ar[i] = ar[j];
ar[j] = swap;
}
}
System.out.println(ar[i]); // to print the new order print it inside the array
}
// I wanna do something like that
// System.out.println(ar[S]);
// but of course I cant cause array S is only defined in it's loop
}
}
You can't reuse it, you need to keep the original array stored in another array that stays untouched. Additionally, Arrays are usually declared as int[] ar in Java, instead of int ar[]. Something along the following lines should work as intended:
public class SortingnumbersANDswapping {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int swap;
int[] ar = new int[3]; //{8,10,5}
for (int S = 0; S < ar.length; S++) {
ar[S] = in.nextInt(); //this for loop is used to store numbers in the array
}
System.out.println("::: Original Array :::");
int[] originalArray = Arrays.copyOf(ar, ar.length);
for (int j : originalArray) {
System.out.println(j);
}
System.out.println("::: Sorted Array :::");
for (int i = 0; i < ar.length; i++) {
for (int j = i + 1; j < ar.length; j++) {
if (ar[i] > ar[j]) { //8>10-->F , 8>5 -->T , {5,10,8} the new arrangment we are going to use
swap = ar[i]; // 10>8-->T {5,8,10}
ar[i] = ar[j];
ar[j] = swap;
}
}
System.out.println(ar[i]); // to print the new order print it inside the array
}
}
}
You can do a copy of the array using the copyOf method from the Arrays library (java.util.Arrays) before you start changing the array.
Here you can find some different approaches - https://www.softwaretestinghelp.com/java-copy-array/amp/
You can use System.out.print(Arrays.toString(arr)); to print the entire array.
public static void main(String... args) {
int[] arr = readArray(3);
System.out.print(Arrays.toString(arr));
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < ar.length; j++) {
if (arr[i] > arr[j]) {
swap(arr, i, j);
System.out.print(Arrays.toString(arr));
}
}
}
}
private static int[] readArray(int size) {
System.out.format("Enter %d elements:\n", size);
Scanner scan = new Scanner(System.in);
int[] arr = new int[size];
for(itn i = 0; i < arr.length; i++)
arr[i] = scan.nextInt();
return arr;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}

Is this a selection sort or a bubble sort?

Is this a selection sort? I think it is Bubble Sort because I'm using (dot)compareTo. I look at different sources on the internet so I can make one. Here is the codes.
import java.util.Arrays;
public class SelectionSort {
public static void main(String args[]) {
String[] row = {"apple", "orange", "banana", "grapes", "mango", "avocado"};
int min = row.length;
for(int m = 0; m < min-1; m++) {
for (int n = m+1; n < row.length; n++) {
if(row[m].compareTo(row[n]) > 0){
String bar = row[m];
row[m] = row[n];
row[n] = bar;
}
}
}
System.out.println("Expected Outcome: " + Arrays.toString(row));
}
}
this is not selection sort
I selection sort in each iteration you find minimum value and put it to the proper location. See this picture
A simple implementation show here:
https://www.javatpoint.com/selection-sort-in-java
public class SelectionSortExample {
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
public static void main(String a[]){
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);//sorting array using selection sort
System.out.println("After Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
}
}
It is not Selection Sort (Milad already answered this), but it is also not Bubble Sort.
The way you can tell that it is not bubble sort, is because bubble sort compares pairs of items that are next to each-other (ex: compares items at index 0-1, 1-2, 2-3... and swaps if necessary). In your code, when m=0, the inner loop will compare item at index 0 with all the other items in the array.
Bubble Sort in Java:
public void sort( int[] array) {
boolean isSorted;
for (var i = 0; i < array.length; i++) {
isSorted = true;
for (var j = 1; j < array.length - i ; j++)
if (array[j] < array[j - 1]) {
swap(array, j, j - 1);
isSorted = false;
}
if (isSorted)
return;
}
}
private void swap(int[] array, int index1, int index2) {
var temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}

Sort an array, nearlly done, just need to reset the minimum

I got το code an array sort for exam preparing. I am already done, the only prob is that my minimum variable is not resetting it self. And I can't put it "null"
Maybe you got an idea... In the beginning I put min = c[0][0]; But if this is the smallest number. It won't work. :/
public class Sort {
public static void main(String[] args) {
int[] a = {3,2,-1,-2,-5,4};
specialSort(a);
}
static void specialSort(int[] a) {
try {
int[] b = new int[a.length];
int[][] c = new int[a.length][2];
for (int k = 0; k<a.length; k++) {
for (int l = 0; l<2; l++) {
if (l == 0) {
c[k][l] = a[k];
} else {
c[k][l] = 0;
}
}
}
int min, minindex;
for (int j=0; j<c.length; j++) {
for (int i=0; i<c.length; i++) {
if (c[i][1] == 0) {
min = c[i][0];
if (min > c[i][0]) {
min=c[i][0];
minindex = i;
}
}
}
b[j] = min;
c[minindex][1] = 1;
}
for(int i=0; i<c.length; ++i) {
//for(int j=0; j<2; j++) {
System.out.print(b[i]+" ");
System.out.println();
}
} catch (IllegalArgumentException e) {
System.out.println("dulli");
}
}
}
If I understand correctly what you're saying and what your problem is, why don't you try setting min initially to
Integer.MAX_VALUE
or
Long.MAX_VALUE
depending on the type of your data, so that you will replace it somehow with one of the numbers from your input, because for sure some number from your input will be smaller than the largest number java can represent? I think it should work if you do it this way

How to fix array index out of bounds error?

The error that I am getting
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 610
at Fib.sorted(Fib.java:67)
at Fib.main(Fib.java:17)
My code
public class Fib
{
public static void main(String args[])
{
System.out.println(Arrays.toString( fiblist) );
System.out.println(Fib.add());
System.out.println(Fib.square());
System.out.println(Fib.reversal());
System.out.println(Fib.sorted());
}
public static int fiblist[] = {1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765};
public static int fiblen = fiblist.length;
public Fib()
{
// Do nothing
}
public static ArrayList<Integer> sorted()
{
ArrayList sorted = new ArrayList();
for(int counter = 0; counter < fiblist[4]; counter++ )
{
int temp1 = fiblist[counter];
System.out.println("Elements stored " + temp1);
}
for(int counter = fiblist[14]; counter < fiblist[19]; counter++)
{
int temp2 = fiblist[counter];
System.out.println("Last Elements stored " + temp2);
}
return sorted;
}
}
I'm trying to store the last 5 elements of my array in temp 2.
Then I will switch them.
Is there an easier way to do this?
Switch the first five elements of an array with the last five?
How would you switch them with a for loop?
You are confusing array index and value. fiblist[19] is 6765. You want your counters to go from 0 to 4 and 14 to 19, not fiblist[19].
for(int counter = 0; counter < 4; counter++ )
{
int temp1 = fiblist[counter];
System.out.println("Elements stored " + temp1);
}
for(int counter = 14; counter < 19; counter++)
{
int temp2 = fiblist[counter];
System.out.println("Last Elements stored " + temp2);
}
This works
for(int i=0;i<fiblist.length;i++){
System.out.print(fiblist[i]+",");
}
System.out.println();
for (int i=0;i<5;i++){
temp=fiblist[i];
fiblist[i]=fiblist[fiblist.length-i-1];
//the first ellement= the last
//the second=second from last...
fiblist[fiblist.length-1-i]=temp;
}
for(int i=0;i<fiblist.length;i++){
System.out.print(fiblist[i]+",");
}
Output:
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,
6765,4181,2584,1597,987,8,13,21,34,55,89,144,233,377,610,5,3,2,1,1,
Try this. It's a sorting algorithm (A fairly poor one though)
public static void sort(int[] a) {
int iMin;
int n = a.length;
for (int j = 0; j < n-1; j++) {
iMin = j;
for (int i = j+1; i < n; i++) {
if (a[i] < a[iMin]) {
iMin = i;
}
}
if(iMin != j) {
swap(j, iMin, a);
}
}
}
public static void swap(int i, int j, int[] arr){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

sorting algorithm is not working

I need to sort in ascending order as I add object to my generic class (I'm using strings).
I'm using selection sort, but it is not working.
I don't know if it is the correct way of doing this, so would appreciate the input.
OrderSet class
public class OrderSet<T extends Comparable> implements Set<T> {
private T[] items;
private int size;
public OrderSet()
{
items = (T[]) new Comparable[5];
}
#Override
public void add(T s)
{
if(size >= items.length)
{
items = grow(items);
}
for(int i = 0; i < items.length; i++)
{
if(items[i] == null)
{
items[i] = s;
size++;
break;
}
}
if(size > 1)
{
for (int i = 0; i < size-1; i++)
{
for(int j = 1; j < size; j++)
{
T tmp;
if (items[i].compareTo(items[j]) > 0)
{
tmp = items[i];
items[i] = items[j];
items[j] = tmp;
}
}
}
}
}
#Override
public void show()
{
for(T a : items)
{
if(a != null)
System.out.print(a+", ");
}
}
public T[] grow(T[] a)
{
T[] newA = (T[]) new Comparable[a.length+5];
System.arraycopy(a, 0, newA, 0, a.length);
return newA;
}
}
main
public class Main {
public static void main(String[] args) throws IOException
{
OrderSet<String> s1 = new OrderSet<>();
WordCount s2 = new WordCount();
Scanner input = new Scanner("the boy plays in the park with dog");
while (input.hasNext())
{
String w = input.next();
s1.add(w);
}
s1.show();
System.out.println();
}
}
I think it's your Sort Algorithm that is wrong. Ardentsonata is right, you use a Bubblesort algorithm but there is a mistake:
for (int i = 0; i < size-1; i++) {
for(int j = 1; j < size; j++){
T tmp;
if (items[i].compareTo(items[j]) > 0) {
tmp = items[i];
items[i] = items[j];
items[j] = tmp;
}
}
}
The Problem is the start value of the second loop, you want to check if any other element - except the ones you already sorted is bigger than the element you want to sort at the moment.
So your second loop needs this head:
for(int j = (i+1); j < size; j++)
so you really sort the array.
Otherwise you were uncontrollable switching your values aroung, because after you switched something to the second slot you switch it back in the next iteration.
Hope that helps !
What you seem to be doing is a bubble sort as you add in items, the generic form of a selection sort is as follows:
for(int i = 0; i<arr.length - 1; i++)
{
int smallest = i;
for(int j = i + 1; j< arr.length; j++)
{
if(arr[j].compareTo(arr[smallest]) > 0)
smallest = j;
}
if(smallest < arr.length && smallest != i)
swap(arr[i], arr[smallest]);
}
You could do it swapping the largest into the last index, but this should work as well. Note, swap is just a placeholder psuedocode for the actual swapping.
Use java.util.TreeSet< T >, which implements SortedSet< T >.
It's better to use String compare concept in this case
class City {
public static void main (String args[])
{
int i,j;
String temp;
String s[] = new String[6];
for(i=0; i<6; i++)
s[i]=args[i];
for(i=0;i<6;i++){
for(j=0;j<6-i-1;j++){
if(s[j].compareTo(s[j+1])>0)
{
temp=s[j];
s[j]=s[j+1];
s[j+1]=temp;
}
}
}
for(i=0; i<6; i++)
{
System.out.println(s[i]);
}
}}

Categories

Resources