I've tried many different variations, and I keep getting the same problem. After selectio nsort runs, the number of items outputted, does not match the size of my array. I've been running through with any array of size 10, yet the output does not contain 10 numbers. However, the output of selection sort is sorted.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Sorts {
public static Integer[] createArray(int size) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < size; i++)
list.add(i);
Collections.shuffle(list);
Integer[] array = list.toArray(new Integer[list.size()]);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
return array;
}
public static void selectionSort(Integer[] array) {
Integer min;
for (Integer i = 0; i < array.length - 1; i++) {
min = i;
for (Integer j = i + 1; j < array.length; j++) {
if (array[j].compareTo(array[min]) > 0) {
min = j;
}
}
if (min != i) {
Integer temp = array[i];
array[i] = array[min];
array[min] = temp;
System.out.print(array[i]);
}
}
}
public static void main(String args[]) {
int number = 10;
Integer[] list = createArray(number);
System.out.println("");
selectionSort(list);
}
}
Whenever you make a swap, you print out a number. But in an array of 10 elements, you'll only make 9 swaps -- the final element will already be in its correct place! To fix this, add System.out.print(array[array.length - 1]); to the end of your function.
Also, if the minimum element happens to be i, then no swap will be performed and no element printed. This still sorts the array, but if you want it to be printed out, you could remove the if (min != i) statement and simply do a swap on every pass through the list.
You should also take a look at using ints rather than Integers. An Integer is generally slower than an int and you usually only use them when Java wants an object.
Related
I have the code for bubble sorting down below. I was wondering how I would be able to run more efficient and loop less amount of times
package bubbleSort;
public class BubbleSort {
public static void main(String[] args) {
// initialize array to sort
int size = 10;
int[] numbers = new int[size];
// fill array with random numbers
randomArray(numbers);
// output original array
System.out.println("The unsorted array: ");
printArray(numbers);
// call the bubble sort method
bubbleSort(numbers);
// output sorted array
System.out.println("The sorted array: ");
printArray(numbers);
}
public static void bubbleSort(int tempArray[]) {
//bubble sort code goes here (you code it)
// loop to control number of passes
for (int pass = 1; pass < tempArray.length; pass++) {
System.out.println(pass);
// loop to control number of comparisions for length of array - 1
for (int element = 0; element < tempArray.length - 1; element++) {
// compare side-by-side elements and swap tehm if
// first element is greater than second elemetn swap them
if (tempArray [element] > tempArray [element + 1]) {
swap (tempArray, element, element + 1);
}
}
}
}
public static void swap(int[] tempArray2,int first, int second) {
//swap code goes here (you code it)
int hold; // temporary holding area for swap
hold = tempArray2 [first];
tempArray2 [first] = tempArray2 [second];
tempArray2 [second] = hold;
}
public static void randomArray(int tempArray[]) {
int count = tempArray.length;
for (int i = 0; i < count; i++) {
tempArray[i] = (int) (Math.random() * 100) + 1;
}
}
public static void printArray(int tempArray[]) {
int count = tempArray.length;
for (int i = 0; i < count; i++) {
System.out.print(tempArray[i] + " ");
}
System.out.println("");
}
}
Any help would be greatly appreciated. I am new to coding and have been very stumped on how to improve efficiency and have it loop less times.
Bubble sort is an inefficiency sorting algorithm and there are much better sorting algorithm.
You can make a bubble sort more efficient, its called Optimized Bubble Sort (It is still quite inefficient)
Optimized bubble sort in short is, - you pass n times , but on the every iteration you 'bubble' the biggest (or smallest) element to the end of the array. Now that last item is sorted, so you don't have to compare it again.
I wrote this code last year, not to sure if it still works:
public static void bubbleSort_withFlag(Integer[] intArr) {
int lastComparison = intArr.length - 1;
for (int i = 1; i < intArr.length; i++) {
boolean isSorted = true;
int currentSwap = -1;
for (int j = 0; j < lastComparison; j++) {
if (intArr[j] < intArr[j + 1]) {
int tmp = intArr[j];
intArr[j] = intArr[j + 1];
intArr[j + 1] = tmp;
isSorted = false;
currentSwap = j;
}
}
if (isSorted) return;
lastComparison = currentSwap;
}
}
Here you can read on optimized bubble sort
Here you can find a list of different sorting algorithms that could be more efficient depending on your scenario.
I know the title is really bad but I spent like 10 minutes thinking of a way to describe my problem in a concise way and couldn't.
This program is supposed to create a numUnique() static method that returns the amount of unique numbers in an array. So, for example, if I have an array with {2, 4, 2, 7, 16, 4} the amount of unique numbers would be 4 (2, 4, 7 and 16).
I was writing the code to find the duplicates in my array, then I realized that I didn't know what to do with it when I had the duplicates, and I've been breaking my head trying to think of a solution but I can't.
Here is the code so far:
public class Unique {
public static void main(String[] args) {
int[] numbers = {1, 6, 2, 14, 6, 8, 2, 1, 23};
numUnique(numbers);
}
public static void numUnique(int[] array){
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j])
//code here
}
}
}
}
My understanding is you to count (not return them all) the number of unique elements in the array. You are attempting to look all the way down, but it's enough to track the number of duplicates as you go. This code looks back to see if the current entry duplicates the previuos one (which works because you sorted, which was a good step).
import java.util.Arrays;
public class Unique {
public static void main(String[] args) {
int[] numbers = {
1,
6,
2,
14,
6,
8,
2,
1,
23
};
System.out.println(numUnique(numbers));
}
public static int numUnique(int[] array) {
Arrays.sort(array);
int dups = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
dups++;
}
}
return (array.length - dups);
}
}
If you want to keep the code that you have so far and sort the list, there are two options that seem to make sense. Where one is to return the number of unique integers, and the other is to return a list of the unique integers.
Returning the number of unique numbers:
public static int numUnique(int[] array) {
ArrayList<Integer> uniques = new ArrayList<>();
Arrays.sort(array);
uniques.add(array[0]);
int prev = array[0];
for (int i = 1; i < array.length; i++) {
if(array[i] != prev){
uniques.add(array[i]);
prev = array[i]
}
}
return uniques.size();
}
Returning the list of unique numbers, would simply require you to return the uniques list, without the .size().
If you want a array instead of a list, you will need to return the following:
return uniques.toArray(new Integer[list.size()]);
If you're using Arrays why not explore it further
private static long numUnique(int[] numbers) {
return Arrays.stream(numbers).distinct().count();
}
Keeping your code as it is:
If You want to know how many non-duplicates are in you array:
public static void numUnique(int[] array) {
Arrays.sort(array);
// Here, make a variable that keeps size of an array
int arrayLenght = array.length;
// Here is our counter:
int duplicates = 0;
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j])
// when you find duplicate, add 1 to our counter:
duplicates++;
}
}
//at the end you can count how many non-duplicates are in the array:
arrayLenght -= duplicates;
System.out.println("There are " + arrayLenght + " non duplicates in our array.");
}
Edit
This solution do not work in every situation.
I know this is not the most optimal way to do this, but the only i know hah:
public static void numUnique(int[] array) {
Arrays.sort(array);
int arrayLenght = array.length;
int duplicates = 0;
for (int i = 0; i < array.length; i++) {
//a little change in our second for-loop:
for (int j = 0; j < array.length; j++) {
if (array[i] == array[j]) {
//Here i'm just summing up the duplicates
duplicates ++;
}
}
// Aaand here, on a console, i print the value (array[i]) and how many duplicates does it have.
//to be exact, if the duplcicates rise only once so it's equal to 1, it means that there is no duplicate of this value (it found itself in the loop).
if (duplicates == 1) {
duplicates = 0;
}
System.out.println(array[i] + " have " + duplicates + "duplicates");
// And what is imporatnt We have to reset our duplication-container!
// so in further loops it will count duplicates for each value in array
duplicates = 0;
}
}
If you find another issue, ask me right away
I am writing code to sort an array in order. I checked some algorithm for sort and merge, however I found that if I just go through the array and compare every 2 elements and swap them and repeat that until the array is sorted.
So if array[I] > array[i++], swap, repeat.
It is not working so far. I also need a break point to avoid stack overflow: I need some help please
Array:
int[] newArray = new int[] {3,9,5,7,4,6,1};
SortArray s = new SortArray();
s.sortThisArray(newArray, 0, 0);
Recursive function:
public String sortThisArray(int[] array, double counter, double a)
{
int swap0 = 0;
int swap1 = 0;
if (a > 1000)
{
return "reached the end" ;
}
for (int i =0; i<array.length; i++)
{
if (array[i] > array[i++])
{
swap0 = array[i];
swap1 = array[i++];
array[i++] = swap0;
array[i] = swap1;
counter = counter++;
a = array.length * counter;
sortThisArray (array, counter, a);
}
}
for (int j = 0; j<array.length ; j++)
{
System.out.println(array[j]);
}
return "completed";
}
}
What you are searching for is recursive bubble sort algorithm.
The main error is confusing i++ (which increments i every time) with i+1, that is only the position in the array after i, without incrementing. Then, there is no need to use double for counter, and also the a variable is not needed. You need only the length of the current segment, this way:
import java.util.*;
public class RecursiveBubbleSort {
public static void main(String[] args) throws Exception {
int[] newArray = new int[] {3,9,5,7,4,6,1};
sortThisArray(newArray, newArray.length);
System.out.println("Sorted array : ");
System.out.println(Arrays.toString(newArray));
}
public static int[] sortThisArray(int[] array, int n) {
if (n == 1) {
return array; //finished sorting
}
int temp;
for (int i = 0; i < n-1; i++) {
if (array[i+1] < array[i]) {
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}
return sortThisArray(array, n-1);
}
}
The ++ operator evalutes separately. So in the case i++, we will read i and then increment it by 1. And the other way around, ++i, would first apply the increment to i, and then read i. So when you want to check for the next element in the array, [i+1] is what you are looking for. With the same reasoning, can you figure out whats wrong with this line?
counter = counter++;
And do we even need it?
So I created an array with random numbers, i printed and counted the repeated numbers, now I just have to create a new array with the same numbers from the first array but without any repetitions. Can't use ArrayList by the way.
What I have is.
public static void main(String[] args) {
Random generator = new Random();
int aR[]= new int[20];
for(int i=0;i<aR.length;i++){
int number=generator.nextInt(51);
aR[i]=number;
System.out.print(aR[i]+" ");
}
System.out.println();
System.out.println();
int countRep=0;
for(int i=0;i<aR.length;i++){
for(int j=i+1;j<aR.length-1;j++){
if(aR[i]==aR[j]){
countRep++;
System.out.println(aR[i]+" "+aR[j]);
break;
}
}
}
System.out.println();
System.out.println("Repeated numbers: "+countRep);
int newaR[]= new int[aR.length - countRep];
}
Can someone help?
EDIT: Can't really use HashSet either. Also the new array needs to have the correct size.
Using Java 8 and streams you can do the following:
int[] array = new int[1024];
//fill array
int[] arrayWithoutDuplicates = Arrays.stream(array)
.distinct()
.toArray();
This will:
Turn your int[] into an IntStream.
Filter out all duplicates, so retaining distinct elements.
Save it in a new array of type int[].
Try:
Set<Integer> insertedNumbers = new HashSet<>(newaR.length);
int index = 0;
for(int i = 0 ; i < aR.length ; ++i) {
if(!insertedNumbers.contains(aR[i])) {
newaR[index++] = aR[i];
}
insertedNumbers.add(aR[i]);
}
One possible approach is to walk through the array, and for each value, compute the index at which it again occurs in the array (which is -1 if the number does not occur again). The number of values which do not occur again is the number of unique values. Then collect all values from the array for which the corresponding index is -1.
import java.util.Arrays;
import java.util.Random;
public class UniqueIntTest
{
public static void main(String[] args)
{
int array[] = createRandomArray(20, 0, 51);
System.out.println("Array " + Arrays.toString(array));
int result[] = computeUnique(array);
System.out.println("Result " + Arrays.toString(result));
}
private static int[] createRandomArray(int size, int min, int max)
{
Random random = new Random(1);
int array[] = new int[size];
for (int i = 0; i < size; i++)
{
array[i] = min + random.nextInt(max - min);
}
return array;
}
private static int[] computeUnique(int array[])
{
int indices[] = new int[array.length];
int unique = computeIndices(array, indices);
int result[] = new int[unique];
int index = 0;
for (int i = 0; i < array.length; i++)
{
if (indices[i] == -1)
{
result[index] = array[i];
index++;
}
}
return result;
}
private static int computeIndices(int array[], int indices[])
{
int unique = 0;
for (int i = 0; i < array.length; i++)
{
int value = array[i];
int index = indexOf(array, value, i + 1);
if (index == -1)
{
unique++;
}
indices[i] = index;
}
return unique;
}
private static int indexOf(int array[], int value, int offset)
{
for (int i = offset; i < array.length; i++)
{
if (array[i] == value)
{
return i;
}
}
return -1;
}
}
This sounds like a homework question, and if it is, the technique that you should pick up on is to sort the array first.
Once the array is sorted, duplicate entries will be adjacent to each other, so they are trivial to find:
int[] numbers = //obtain this however you normally would
java.util.Arrays.sort(numbers);
//find out how big the array is
int sizeWithoutDuplicates = 1; //there will be at least one entry
int lastValue = numbers[0];
//a number in the array is unique (or a first duplicate)
//if it's not equal to the number before it
for(int i = 1; i < numbers.length; i++) {
if (numbers[i] != lastValue) {
lastValue = i;
sizeWithoutDuplicates++;
}
}
//now we know how many results we have, and we can allocate the result array
int[] result = new int[sizeWithoutDuplicates];
//fill the result array
int positionInResult = 1; //there will be at least one entry
result[0] = numbers[0];
lastValue = numbers[0];
for(int i = 1; i < numbers.length; i++) {
if (numbers[i] != lastValue) {
lastValue = i;
result[positionInResult] = i;
positionInResult++;
}
}
//result contains the unique numbers
Not being able to use a list means that we have to figure out how big the array is going to be in a separate pass — if we could use an ArrayList to collect the results we would have only needed a single loop through the array of numbers.
This approach is faster (O(n log n) vs O (n^2)) than a doubly-nested loop through the array to find duplicates. Using a HashSet would be faster still, at O(n).
class arrayDemo {
static void sort2D(int[][] B) {
boolean swap = true;
int oy=0;
int temp=0;
for(int ox=0;ox<B.length;ox++){
while(oy<B[ox].length) {
while(swap) {
swap = false;
for(int ix=0;ix<B.length;ix++) {
for(int iy=0;iy<B[ix].length;iy++) {
if(B[ox][oy]<B[ix][iy]) {
temp = B[ix][iy];
B[ix][iy] = B[ox][oy];
B[ox][oy] = temp;
swap = true;
}
}
}
}
oy++;
}
}
for(int row=0;row<B.length;row++)
for(int col=0;col<B[row].length;col++)
System.out.println(B[row][col]);
}
public static void main(String...S) {
int y[][] = {{10,20,0,30},{10,5,8},{3,9,8,7},{2,3}};
sort2D(y);
}
}
I am trying to sort a 2D array in ascending order.
Input: {{10,20,0,30},{10,5,8},{3,9,8,7},{2,3}};
Output: 30,20,10,10,9,8,8,7,5,3,0,2,3
Can someone help me know what is wrong with my code.
You are comparing elements that are not in the same row or column. Each sub-array should be sorted individually. You might want to reconsider this line if (B[ox][oy] < B[ix][iy]).
That code has a number of problems.
It throws ArrayIndexOutOfBoundsException. This is because all for loop tests test against B.length, which is not correct for inner arrays.
You are comparing every pair of elements, but some pairs are the reverse of other pairs, and the reverse pairs should not be tested. You need to limit the scope of your inner set of for loops, by starting at a different index.
To fix all these problems, the path of least resistance is to dump the 2D array into a 1D array and sort that, which is much easier.
Here is code that has been tested and shown to work:
static void sort2D(int[][] B) {
int count = 0;
for (int[] is : B)
for (int i : is)
count++;
int[] A = new int[count];
count = 0;
for (int[] is : B)
for (int i : is)
A[count++] = i;
int temp;
for (int i = 0; i < A.length; i++)
for (int j = i + 1; j < A.length; j++)
if (A[i] > A[j]) {
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + ",");
}