Counting swaps and comparisons in an array method - java

I need help counting the swaps and comparisons i na selected bubble sort algorithm. I have tried passing in values to change them for each iteration but I cannot figure out how I can successfully implement a counter for the swaps and comparisons.
static void bubbleSort(int[] userArray_Copy, int n, int swaps) {
swaps = 0;
int temp;
for (int i = 0; i < n; i++) {
for (int j = 0 ; j < n-1 ; j++) {
if (userArray_Copy[j] > userArray_Copy[j + 1]){
temp = userArray_Copy[j];
userArray_Copy[j] = userArray_Copy[j+1];
userArray_Copy[j+1] = temp;
swaps++;
}
}
}
}

Related

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;
}

Modifying a static method to add two counters when comparing arrays using for loops in Java

Using this segment of code I already have, I want to modify the selectionSort method to have two counters, one for the number of comparisons, and one for the number of data swaps. Each time two data elements are compared (regardless of whether the items are in the correct order—we're interested in that a comparison is being done at all), increment the comparison counter. Each time two data items are actually swapped, increment the data swap counter.
So far this is what I have tried to add the counters. However, I receive an error "Unresolved compilation problem: counter cannot be resolved to a variable".
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
int counter = 0;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
// Swap list[i] with list[currentMinIndex] if necessary;
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
counter += 1;
}
System.out.println("The size of the sorted array is " + list.length + " and the count is " + counter);
}
I have the main method prepared below.
public static void main(String[] args) {
final int NUM_ELEMENTS = 10;
double[] lo2Hi = new double[NUM_ELEMENTS];
for (int i = 0; i < NUM_ELEMENTS; i++) {
lo2Hi[i] = i + 1;
}
selectionSort(lo2Hi);
double[] hi2Lo = new double[NUM_ELEMENTS];
for (int i = 0; i < NUM_ELEMENTS; i++) {
hi2Lo[i] = 10 - i;
}
selectionSort(hi2Lo);
double[] random = new double[NUM_ELEMENTS];
for (int i = 0; i < random.length; i++) {
random[i] = Math.random();
}
selectionSort(random);
}
Your println() at the end of selectionSort() is trying to acces the variable counter, but counter is "out of scope" at that point. Variables only exist within the pair of {}'s they were declared inside (that's what "scope" is).
Move the int counter = 0; statement out of the for loop, and put it at top of the method. Then it will be in-scope for the print statement.

Java : Selection Sort Logic

I am printing Sorted Array elements using Selection Sort. But I am getting my input array elements as output in same sequence without sorting.
public class SelectionSort {
public static void main(String[] args) {
int[] arr= {1,9,3,0,7};
int n=arr.length;
for(int i=0; i<n-1; i++)
{
int minimumIndex = i;
for(int j=i; j<n; j++)
{
if(arr[j]<arr[minimumIndex])
{
minimumIndex=j;
}
}
int temp=arr[i];
arr[i]=arr[minimumIndex];
arr[i]=temp;
}
for(int e: arr)
{
System.out.print(e+" ");
}
}
}
Expected o/p : 0 1 3 7 9
Actual o/p: 1 9 3 0 7
In Your method code, the actual problem is swapping elements,
the Sequence needs to be like this as below,
int temp=arr[minimumIndex];
arr[minimumIndex]=arr[i];
arr[i] =temp;
instead of
int temp=arr[i];
arr[i]=arr[minimumIndex];
arr[i]=temp;
There are two issues I see. One is the way you are swapping the items. You need to replace the item where you found the minimum index. Also, your J index should start one after your I index. You can assume that the one before it is the smallest as you are looping through. I have changed a few pieces of the code and tested it and it works fine for me.
for (int i = 0; i < arr.length - 1; i++)
{
int minimumIndex = i;
for (int j = i + 1; j < arr.length; j++)
{
if (arr[j] < arr[minimumIndex])
{
minimumIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minimumIndex];
arr[minimumIndex] = temp;
}

SelectionSort and for loop

I have a question regarding SelectionSort.
Please, take a look at my Code:
public static int[] sortiert(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[j] > array[i]) {
int speicher = array[i];
array[i] = array[j];
array[j] = speicher;
}
}
}
return array;
Can you please tell me why I have j = i + 1 in the second for-loop?
It bothers me...
array.length - 1 in the first loop is clear.
It would be nice to get an answer detailed
public static class SelectionSort
{
static int min;
public static void Sort(int[] data)
{
for (int i = 0; i < data.Length; i++)
{
for (int j = 0; j < data.Length; j++)
{
min = j;
if (data[i] < data[j])
Swap(x: ref data[i], y: ref data[min]);
}
}
}
private static void Swap(ref int x, ref int y)
{
x = x+y;
y = x-y;
x = x-y;
}
}
The sortiert method is running through the array multiple times. With every pair of elements, if the second element (the one later in the list) is greater than the first element (if (array[j] > array[i])), then it swaps the two elements, such that eventually the list will be sorted in decreasing order.
The i index represents the "first value" being compared above and the j index represents the "second value" being compared above. Thus, j will always start at i+1 as it must always be after the first value in the list. If j = i in the for loop, then you would be checking array[i] > array[i] because j = i in that case; since a number is never strictly less than itself, this would always return false and is thus an unnecessary operation.

Recursion - Adding the subset of an array

I'm trying to decide if the sum of subset is a set num or not)...
I've read through most of the questions so far here on stackoverflow and have come up with nothing. I think the issue I'm finding is that I want to add together the elements in the combitorial subsets created. All together this should be done recursively. With the current code I have, I'm getting a stackoverflow error for recursion. (ironic)
So to clarify:
int[] array = {1,2,3,4,5};
the subset would be the size of say 2 and combinations would be
{1,2},{1,3},{1,4},{1,5},{2,3},{2,4},{2,5},{3,4},{3,5},{4,5}
from this data I want to see if the subset say... equals 6, then the answers would be: {1,5} and {2,4} leaving me with true as a answer. In respect to the signature I would like to keep it the same because it corresponds with another method (outside of the issue because it only sends the array, n, and num to the method)
public static boolean subset(int[] array, int n, int num) {
int count = 0;
int sum = 0;
int[] subarray = new int[n];
int[] temp = new int[array.length - 1];
int[] copy = array;
subarray[count] = array[0];
for (int i = 0; i < n; i++) {
subarray[count] = array[i];
count++;
System.arraycopy(array, i, temp, 0, n);
}
for (int j = 0; j < subarray.length; j++) {
sum += subarray[j];
if (sum == num)
return true;
}
subset(copy, n, goal);
return false;
}
Not an answer but a plausible idea for one?
for (int i = 0; i < array.length; i++) {
// New sublist to store values from 0 to i
int[] list = new int[array.length - 1];
for (int j = 0; j < array.length; j++) {
list[j] = array[j+1];
}
// Here you call this recursively with your Parent list from i+1
// index and working list from 0 to i
subsetSum(list, n, goal);
}
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
if (sum == goal) {
return true;
}
return false;

Categories

Resources