Java - Selection Sort - only switching once - java

So the first switch definitely occurs between the lowest value 3, and 5, but it doesn't keep going after that. This makes me think there is something wrong with one of the for loops?
public class SelectionSort
{
public static void main (String[] args)
{
int [] list;
list = new int[5];
list[0] = 4;
list[1] = 5;
list[2] = 12;
list[3] = 9;
list[4] = 3;
for (int i = 0; i < list.length-1; ++i) {
int index = i;
for (int j = 1; j < list.length; ++j) {
if (list[j] < list[index]) {
int temp = list[j];
list[j] = list[index];
list[index] = temp;
}
}
}
for (int k = 0; k < list.length; ++k) {
System.out.print(list[k] + ", ");
}
}
}

Short versiĆ³n:
for (int i = 0; i < list.length-1; i++)
for (int j = i+1; j < list.length; j++)
if (list[j] < list[i]) {
int temp = list[j];
list[j] = list[i];
list[i] = temp;
}
for (int k = 0; k < list.length; k++) {
System.out.print(list[k] + ", ");
}

after if (list[j] < list[index]) {, you have to update index if boolean statement gets satisfied so you need to index = j and do the swap after
see follwing :
public class MySelectionSort {
public static int[] doSelectionSort(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;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}

for (int i = 0; i < list.length; ++i) {
int index = i;
for (int j = i + 1; j < list.length; ++j) {
if (list[j] < list[index]) {
index = j; }}
if (index != i) {
int temp = list[i];
list[i] = list[index];
list[index] = i; }}
To cut down on the number of swaps, the loop on j should only be looking the best item to swap with item i. There should be at most one swap for each value of i. (That's what makes it a Selection sort. If you do multiple swaps for each i, you might as well be doing Bubble Sort.
But that's for efficiency. The reason your code isn't working is that you start the loop on j at j = 1 instead of j = i + 1.

Related

Java sorting algorithm problems

I need to make a programm in java with the selection sort algorithm. So i tried this to do that but the code doesn't works.
Problem with this code is that it doesn't swap numbers. Instead, it replaces array[i] with the minimum number found. You can modify your loop like this to do the swapping.
for (int i = 0; i < array.length; i++) {
int minIndex = i;
for (int j = i; j < array.length; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
if (array[minIndex] != array[i]) {
int wert = array[minIndex];
array[minIndex] = array[i];
array[i] = wert;
}
}
For selection sort use this method
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;
}
}
If you need an ascend order just use:
Arrays.sort(array) from java.util library
But if you need to sort descending I'd suggested to reffer to:
https://www.baeldung.com/java-sorting-arrays

What is wrong in my bubble sort using ArrayList?

What is wrong in my bubble sort in ArrayList? It was not sorted . I am a beginner.
public static ArrayList < Integer > bubbleSort(ArrayList < Integer > ar) {
for (int i = 0; i < ar.size() - 1; i++) {
int indexMax = i;
for (int j = 1; j < ar.size(); j++) {
if (ar.get(indexMax) > ar.get(j)) {
indexMax = j;
}
}
if (indexMax != i) {
int temp = ar.get(i);
ar.set(i, ar.get(indexMax));
ar.set(indexMax, temp);
}
}
return ar;
}
Are you sure you should start from 2nd element (j=1) every time?
Try j=i. i.e.,
public static ArrayList<Integer> bubbleSort (ArrayList<Integer> ar) {
for (int i = 0; i < ar.size() - 1; i++) {
int indexMax = i;
for (int j = i; j < ar.size(); j++) {
if (ar.get(indexMax) > ar.get(j)) {
indexMax = j;
}
}
if (indexMax != i) {
int temp = ar.get(i);
ar.set(i, ar.get(indexMax));
ar.set(indexMax, temp);
}
}
return ar;
}
P.S this will sort your array in ascending order.
Your swapping code block looked like it was outside of loop, so the only one swap occurred for one iteration of main loop.
You are also doing unnecessary comparing of elements, starting your inner loop with precondition j = 1. You should start it from i, as after some iterations of outer loop range from 0 to i will be already sorted.
I think you can use a simpler approach.
for (int i = 0; i < ar.size() - 1; i++) {
for (int j = i; j < ar.size(); j++) {
if (ar.get(j) < ar.get(i)) {
Integer temp = ar.get(j);
ar.set(j, ar.get(i));
ar.set(i, temp);
}
}
}
As you can see, swapping takes place inside of the inner loop, and it also skips already sorted part of collection.
You can do sorting like this:
for(int out=inputArray.size()-1; out>0; out--){
for(int j=1; j<=out; j++){
if(inputArray[j-1]<inputArray[j]){
//Swap the elements
int temp = inputArray[j];
inputArray[j]=inputArray[j-1];
inputArray[j-1]=temp;
}
}
}
return inputArray;
Can you try that?
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
// swap arr[j+1] and arr[i]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}

How to structure an array of multiple outputs in one array (Java)

My code basically runs through an array, finds the maximum, and then locates the indices correlated with it. The issue I have is that I would like the indices in one array instead of multiple.
For example (actual output):
[1] [2] [3] [4]
Wanted output: [1,2,3,4]
Here is my code:
int index;
int num = myArray[0];
for (int i = 0; i < myArray.length; i++) {
if (num < myArray[i]) {
num = myArray[i];
}
}
for (int j = 0; j < myArray.length; j++) {
if(num == myArray[j]){
index = j;
System.out.println("[" + j + "]");
}
}
I don't know how to do this without redoing all the code. Thanks.
int index;
int num = myArray[0];
for (int i = 0; i < myArray.length; i++) {
if (num < myArray[i]) {
num = myArray[i];
}
}
System.out.print("[");
int count = 0;
for (int j = 0; j < myArray.length; j++) {
if(num == myArray[j]){
index = j;
if(count++ > 0)
System.out.print(",");
System.out.print(j);
}
}
System.out.println("]");
int maxValue = myArray[0];
int countMaxValues = 1;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > maxValue) {
maxValue = myArray[i];
countMaxValues = 1;
}
else if (myArray[i] == maxValue) {
countMaxValues++;
}
}
int maxValueIndices = new int[countMaxValues];
int i = 0;
for (int j = 0; j < myArray.length; j++) {
if(myArray[j] == maxValue){
maxValueIndices[i++] = j;
}
}
System.out.println(Arrays.toString(maxValueIndices));

Please clarify me thats wrong in my selection sort code

In this method only one element is getting sorted rest of the elements are are not sorted.
Please help me to find where the actual problem is
private static int[] selectSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int min_Ele = i;
for (int j = 1; j < n; j++) {
if (arr[j] <= arr[min_Ele]) {
min_Ele = j;
}
}
if (i != min_Ele) {
int tmp = arr[i];
arr[i] = arr[i = min_Ele];
arr[min_Ele] = tmp;
}
}
return arr;
}
Your mistake is that your inner loop should start from i+1 and not from 1.
public static int[] selectSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int min_Ele = i;
for (int j = i+1; j < n; j++) {
if (arr[j] <= arr[min_Ele]) {
min_Ele = j;
}
}
if (i != min_Ele){
//swap
int tmp = arr[i];
arr[i] = arr[i = min_Ele];
arr[min_Ele] = tmp;
}
return arr;
}
private static int[] selectSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
int min_Ele = i;
for (int j = i+1; j < n; j++) {
if (arr[j] <= arr[min_Ele]) {
min_Ele = j;
}
}
if (i != min_Ele) {
int tmp = arr[i];
arr[i] = arr[min_Ele];
arr[min_Ele] = tmp;
}
}
return arr;
}

Finding the largest row and column, solution is inconsistent

Where is the logic error?.. Sometimes the solution is correct and sometimes it is not. The program is suppose to calculate the row with the greatest sum and column with the greatest sum. For example:
1 1 1 1
0 0 1 0
0 0 1 0
0 0 1 0
Then the output would be:
largest row = 0
largest column = 2 //since count starts at 0
This is what I have:
import java.util.Random;
public class LargestRowAndColumn {
public static void main(String[] args) {
Random f = new Random();
int[][] m = new int[4][4];
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
System.out.println("The largest row is index: " + computeRow(m));
System.out.println("The largest column is index: " + computeColumn(m));
}
public static int computeRow(int[][] m) {
int[] count = new int[m.length];
int sum;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[i][j];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
public static int computeColumn(int[][] m) {
int[] count = new int[m.length];
int sum = 0;
for (int i = 0; i < 4; i++) {
sum = 0;
for (int j = 0; j < 4; j++) {
sum = sum + m[j][i];
}
count[i] = sum;
}
int maxIndex = 0;
for (int i = 0; i < i + 1; i++) {
for (int j = count.length - 1; j >= i; j--) {
if (count[i] < count[j]) {
maxIndex = j;
break;
}
}
}
return maxIndex;
}
}
Your maxIndex nested loop is too complex. It should be a single loop, checking the current max value seen so far with the current item in the loop. Something like this:
int maxIndex = 0;
for (int i = 1; i < count.length; i++) {
if (count[i] > count[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
Your code is correct , but
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(2);
}
}
for (int i = 0; i < m.length; i++) {
for (int j = 0;j < m[0].length; j++) {
System.out.print(m[i][j] + " ");
}
Because of the two loops:
You are creating two random 2-dimensional array instead of one.
There is one which is being printed and the other one which is not being printed but being used for index values you require so do :
System.out.print("Index" + "\t0"+"\t1"+"\t2"+"\t3" +"\n");
System.out.print("--------------------------------------------\n");
for (int i = 0; i < m.length; i++) {
System.out.print(i+ "|\t");
for (int j = 0;j < m[0].length; j++) {
m[i][j] = f.nextInt(101);
System.out.print(m[i][j] + " \t");
}
System.out.println();
}
This will also print the index, which may assist you
Why you made your job difficult. Make 2 loops, 1 for calculating the row with biggest sum, 1 for calculating the line with the bigger sum.
You don't need an int array count[i]. In your example you calculate the row with the greatest sum, you don't need to know the sum of every row after the for loop finished, so you can use a simple int bigRow.
int bigRow = 1, sumRow = 0;
// We assume that 1st row is the biggest
// Calculate the sumRow
for (int j=0;j<n;j++)
sumRow = sumRow + m[i][j] ;
// At this moment our maximum is row 1 with its sum.
// Now we compare it with the rest of the rows
// If another row is bigger, we set him as the biggest row
for ( int i=1;i<n;i++) // We start with row 2 as we calculated the 1st row
{ int auxRow = 0;
for (int j=0;j<m;j++)
{ auxRow = auxRow + m[i][j] ; }
if (auxRow > sumRow ) { auxRow=sumRow ; bigRow = i;}
}
Do the same with lines.
int bigLine = 1, sumLine = 0 ;
Let me know if you have another problem.

Categories

Resources