java - Selection Sort - java

I want to implement a selection alignment that receives 10 integers and organizes them in ascending order.
However, when my code is operated, other things work normally, but only the first integer is not aligned.
Please let me know how to fix the code.
public static void sort(int[] array) {
Scanner sc = new Scanner(System.in);
System.out.println("put the int");
for (int i =0;i <array.length;i++) {
System.out.print((i+1)+": ");
int n = sc.nextInt();
array[i] = n;
for (int j = 1; j < array.length;j++) {
if (array[i] < array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for (int a=0; a< array.length; a++) {
System.out.print(array[a]+" ");
}
}
public static void main(String[] args) {
int[] my_array = {0,0,0,0,0,0,0,0,0,0};
sort(my_array);
}
}

You should set
int j = 0
in the inner for

If you want to implement Selctionsort
initialize the inner for with int j = i+1
change numbers if array[i] is greater than array[j] not the other way around
for (int i =0;i <array.length;i++) {
int minValue = array[i];
for (int j = i +1; j < array.length;j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for (int a=0; a< array.length; a++) {
System.out.print(array[a]+" ");
}

You need to read the entire array in first, then you can sort it. Also, I don't consider your algorithm a true selection sort. In selection sort, you must find the minimum in the array of unsorted data. Then you swap. Your algorithm doesn't do that exactly.
To illustrate, I have broken the code into functions.
// Find the minimum value in the array, starting the search at "start"
// Returns the index of the minimum
static int findMinIndex(int[] array, int start)
{
int min = array[start];
int minIndex = start;
for (int i = start + 1; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
minIndex = i;
}
}
return minIndex;
}
// Swap 2 elements of an array
static void swap(int[] array, int index1, int index2)
{
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
// Selection sort the array, ascending
static void selectionSort(int[] array)
{
for (int i = 0; i < array.length; i++) {
// First find the minimum from i to the end of the array...
int minIndex = findMinIndex(array, i);
// ...then swap
if (minIndex != i) {
swap(array, i, minIndex);
}
}
}

Related

why my selection sort program is not working?

public class first {
public static void main(String args[]){
int arr[]={5,4,1,3,2};
for(int i=0; i<arr.length-1;i++){
int smallest=arr[i];
for(int j=i+1; j<arr.length;j++){
if(smallest>arr[j]){
smallest=arr[j];
}
}
//swap
int temp=smallest;
smallest=arr[i];
arr[i]=temp;
}
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}
}
i have done this problem by getting the smallest in terms of index number
and the program works properly .
but when i am taking smallest in terms of number present at index number ,
this program did not work.your text
you need to save the smallest number index not the number it self so you know the positions to make the swap
for (int i = 0; i < arr.length - 1; i++) {
int indexOfSmallestNum = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[indexOfSmallestNum] > arr[j]) indexOfSmallestNum = j;
}
int temp = arr[i];
arr[i] = arr[indexOfSmallestNum];
arr[indexOfSmallestNum] = temp;
}

bubble sort problem number of passes (wrong output coming)

Write a bubble sort program that prints the number of swaps made after M number of iterations (In this case, ‘M’ should be an input value).
For example, if M = 0, the bubble sort program will perform 0 swaps in 0 iterations.
In bubble sort, an iteration is defined as the total number of times the outer loop runs. Assume that:
M <= the array size and
the program sorts in descending order.
The code should ask the user to input the values for M, the array size, and finally the elements of the array. So, there will be three types of inputs —
Input 1: The value of M
Input 2: The size of the array
Input 3: The elements inside the array
Sample Input:
2
4
1
2
3
4
Sample Output:
5
Please help me in solving the Bubble Sort Problem. Here I run the program but I am getting 3 in place of 5.
here's my code :
package com.company;
import java.util.*;
class Source {
static int totalBubbleSortSwaps(int[] array, int M) {
int pass=0;
boolean isDone;
for (int k = 0; k < ( array.length-1 ); k++) {
isDone=true;
for (int j = 0; j < array.length-k-1; j++) {
if (array[j] < array[j+1])
{
//isDone=false;
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
pass++;
}
}
if(isDone){
break;
}
}
//for (pass =1; pass <m; ++pass){
//for (k = 0; k < size; k++)
return pass;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int size = scanner.nextInt();
int array[] = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
System.out.println(totalBubbleSortSwaps(array, m));
}
}
count the number of swaps made after M runs of the outer loop.
A couple observations.
you are sorting the values in descending order. Is that correct?
you need to only count the swaps while m > 0.
after each outer loop, decrement m by 1 (for each iteration of the outer loop).
you are not setting your isDone flag.
Here is what I came up with. I changed pass to swaps.
public class BubbleSort {
static int totalBubbleSortSwaps(int[] array, int m) {
int swaps = 0;
boolean isDone;
for (int k = 0; k < (array.length - 1); k++) {
isDone = true;
for (int j = 0; j < array.length - k - 1; j++) {
if (array[j] > array[j + 1]) { // <----- changed to > from <
isDone=false;
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
if (m > 0) {
swaps++; // <---- update swap count
}
}
}
if (isDone) {
break;
}
m--; <---- decrement m
}
return swaps;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int size = scanner.nextInt();
int array[] = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
System.out.println(totalBubbleSortSwaps(array, m));
}
}
}
import java.util.Scanner;
class Source {
static int totalBubbleSortSwaps(int[] array, int m) {
int swaps = 0;
for (int k = 0; k < m; k++) {
for (int j = 0; j < array.length - k - 1; j++) {
if (array[j] < array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swaps++;
}
}
}
return swaps;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int size = scanner.nextInt();
int array[] = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
System.out.println(totalBubbleSortSwaps(array, m));
}
}
The below code will give you the number of swaps done in bubble sort (descending order) when "M" iterations are done in the outer loop:
import java.util.*;
public class BubbleSortSwaps {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int M = scanner.nextInt();
int size = scanner.nextInt();
int array[] = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
System.out.println(totalBubbleSortSwaps(array, M));
}
}
static int totalBubbleSortSwaps(int[] array, int M) {
int size = array.length;
int totalSwaps = 0;
for (int i = 0; i < M; i++) {
Boolean swap = false;
for (int j = 1; j < size - i; j++) {
int swapTemp = 0;
if (array[j - 1] < array[j]) {
swapTemp = array[j - 1];
array[j - 1] = array[j];
array[j] = swapTemp;
swap = true;
totalSwaps++;
}
}
if (!swap)
break;
}
return totalSwaps;
}
}

Difficulty trying to sort 10 numbers inputted by a user. Must use arrays and a separate method for sorting

My program isn't sorting the numbers at all. It displays them in the order they were initially entered. It must sort them from smallest to largest number. The code below should find the largest number in the array and swap it with the last .the code is below:
import java.util.Scanner;
public class maxSorttt {
public static void main(String[] args) {
double[] ten = new double[10];
Scanner input = new Scanner(System.in);
System.out.print("Enter 10 numbers: ");
for (int i = 0; i < ten.length; i++)
ten[i] = input.nextDouble();
sort(ten);
}
public static void sort(double[] array) {
for (int i = array.length - 1; i < 0; i--) {
double currentMax = array[i];
int currentMaxIndex = i;
for (int x = i - 1; x < -1; x--) {
if (currentMax < array[x]) {
currentMax = array[x];
currentMaxIndex = x;
}
}
if (currentMaxIndex != i) {
array[currentMaxIndex] = array[i];
array[i] = currentMax;
}
}
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
}
}
I believe your problem is here:
for(int i=array.length-1; i<0; i--)
array.length is not less than 0 so the for loop never runs. You probably wanted
for(int i=array.length-1; i>=0; i--)
Be Simple!
public static void selectionSort(double[] arr) {
for (int i = 0; i + 1 < arr.length; i++) {
int minIndex = findMinIndex(arr, i + 1);
if (Double.compare(arr[i], arr[minIndex]) > 0)
swap(arr, i, minIndex);
}
}
private static int findMinIndex(double[] arr, int i) {
int minIndex = i;
for (; i < arr.length; i++)
if (Double.compare(arr[i], arr[minIndex]) < 0)
minIndex = i;
return minIndex;
}
private static void swap(double[] arr, int i, int j) {
double tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}

Modified Bubble Sort

I need to write an algorithm that will take an array of ints and find the k'th largest element in the array. The caveat here is that the runtime must be O(K*n) or better.
My teacher has made it clear this can be done with a modified bubble sort program, but I am unsure as to how I can modify the bubble sort without ruining it, as I would think it necessary to loop through every element of the array. Here is my code (just the shell of the program and an unmodified bubble sort):
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
for (int i = (A.length - 1); i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (sorted[j-1] < sorted[j])
{
temp = sorted[j-1];
sorted[j-1] = sorted[j];
sorted[j] = temp;
}
}
}
return sorted[k-1];
}
Figured it out:
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
for (int i = 0; i < A.length-1; i++)
{
for (int j = 0; j < A.length-i-1; j++)
{
if (sorted[j] > sorted[j+1])
{
temp = sorted[j];
sorted[j] = sorted[j+1];
sorted[j+1] = temp;
}
if(i == (k-1)) return A[A.length-i-1];
}
}
return sorted[A.length-k];
}
The the array has been sorted to the k-th largest element, it has found what it is looking for and can stop the sort and return.
I thought a modified bubble sort just exited early if the list was already sorted?
Wouldn't something like this suffice?
public int kthLargest(int[] A, int k){
int[] sorted = A;
int temp;
bool bSorted = TRUE;
for (int i = (A.length - 1); i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (sorted[j-1] < sorted[j])
{
temp = sorted[j-1];
sorted[j-1] = sorted[j];
sorted[j] = temp;
bSorted = FALSE;
}
}
if(bSorted)
break;
}
return sorted[k-1];
}

Where are comparisons in java sorting methods?

Question: Where are comparisons being made in each separate sorting method?
Also if you know please tell me which method count numbers are wrong and where to place my counters instead.trying to understand where and how many times sorting methods make comparisons.
Method A B
Selection 4950 4950
Bubble 99 9900
Insertion 99 5049
Merge 712 1028
Shell 413 649
Quick 543 1041
Okay so to explain some parts, basically Array A is an array from 1-100 in ascending order. So this should be the minimum number of comparisons.
Array B is 100-1 in descending order. So I believe it should be the maximum number of comparisons. Array C is just randomly generated numbers, so it changes every time.
I feel like my selection and bubble sorts were counted correctly. Feel free to let me know where comparisons are being made that I haven't counted, or if I'm counting wrong comparisons.
Side note: Made some global variable to count the methods that were recursive in multiple sections.
class Sorting
{
static int[] X = new int[100];
static int mergecount = 0;
static int quickcount = 0;
public static void selectionSort(int list[])
{
int count = 0;
int position = 0, n = list.length;
for(int j = 0; j < n-1; j++)
{
position = j;
for(int k = j+1; k < n; k++)
{
count++;
if(list[k] < list[position])
position = k;
}
Swap(list, j, position);
}
System.out.println("counter" + count);
}
public static void Swap(int list[], int j, int k)
{
int temp = list[j];
list[j] = list[k];
list[k] = temp;
}
public static void bubbleSort(int list[])
{
int count = 0;
boolean changed = false;
do
{
changed = false;
for(int j = 0; j < list.length - 1; j++)
{
count++;
if(list[j] > list[j + 1])
{
Swap(list, j, j+1);
changed = true;
}
}
} while(changed);
System.out.println("counter" + count);
}
public static void insertionSort(int list[])
{
int count = 0;
for(int p = 1; p < list.length; p++)
{
int temp = list[p];
int j = p;
count++;
for( ; j > 0 && temp < list[j - 1]; j = j-1)
{
list[j] = list[j - 1];
count++;
}
list[j] = temp;
}
System.out.println("counter" + count);
}
public static void mergeSort(int list[])
{
mergeSort(list, 0, list.length - 1);
System.out.println("counter" + mergecount);
}
public static void mergeSort(int list[], int first, int last)
{
if(first < last)
{
int mid = (first + last) / 2;
mergeSort(list, first, mid);
mergeSort(list, mid + 1, last);
Merge(list, first, mid, last);
}
}
public static void Merge(int list[], int first, int mid, int last)
{
int count = 0;
int first1 = first, last1 = mid;
int first2 = mid + 1, last2 = last;
int temp[] = new int[list.length];
int index = first1;
while(first1 <= last1 && first2 <= last2)
{
if(list[first1] < list[first2])
{
temp[index] = list[first1++];
mergecount++;
}
else
temp[index] = list[first2++];
index++;
mergecount++;
}
while(first1 <= last1)
temp[index++] = list[first1++];
while(first2 <= last2)
temp[index++] = list[first2++];
for(index = first; index <= last; index++)
list[index] = temp[index];
}
public static void shellSort(int list[])
{
int count = 0;
int n = list.length;
for(int gap = n / 2; gap > 0; gap = gap == 2 ? 1: (int) (gap/2.2))
for(int i = gap; i < n; i++)
{
int temp = list[i];
int j = i;
count++;
for( ; j >= gap && (temp < (list[j - gap])); j -= gap)
{
list[j] = list[j - gap];
count++;
}
list[j] = temp;
}
System.out.println("counter" + count);
}
public static void quickSort(int start, int finish, int list[])
{
int count = 0;
int left = start, right = finish, pivot, temp;
pivot = list[(start + finish) / 2];
do
{
while(list[left] < pivot)
{
left++;
quickcount++;
}
while(pivot < list[right])
{
right--;
quickcount++;
}
if(left <= right)
{
temp = list[left];
list[left++] = list[right];
list[right--] = temp;
quickcount++;
}
} while(left < right);
if(start < right)
quickSort(start, right, list);
if(left < finish)
quickSort(left, finish, list);
}
public static void copy(int list[])
{
for(int i = 0; i < list.length; i++)
X[i] = list[i];
}
public static void restore(int list[])
{
for(int i = 0; i < list.length; i++)
list[i] = X[i];
}
public static void displayArray(int list[])
{
for(int k = 0; k < list.length; k++)
System.out.print(list[k] + " ");
System.out.println();
}
public static void main(String args[])
{
int[] A = new int[100];
for(int i = 0; i < A.length; i++)
A[i] = i + 1;
int[] B = new int[100];
int q = 100;
for(int i = 0; i < B.length; i++)
B[i] = q--;
int[] C = new int[100];
for(int i = 0; i < C.length; i++)
C[i] = (int)(Math.random() * 100 + 1);
displayArray(A);
copy(A);
selectionSort(A);
displayArray(A);
restore(A);
}
Note that QuickSort performance is greatly influenced by your choice of the pivot. With both of your test arrays sorted (ascending / descending) and because you are picking pivot as array[length/2] you are actually always picking the best pivot. So your test case B won't generate maximum number of comparisons for quicksort. If you were picking array[0] as pivot you'd get maximum number of comparisons for test case A and B.
The easiest way to count comparisons is to use a compare function and do it in there.
static int compareCount = 0;
int compareInt(int a, int b) {
compareCount++;
return a - b; // if 0 they are equal, if negative a is smaller, if positive b is smaller
}
Now just use compareInt in all your algorithms and you'll get an accurate count. You'll have to reset compareCount between each run though.

Categories