I cannot seem to make sense of this particular algorithm. It seems to be a bubblesort but not in a traditional sense. What is it?
public static void main(String[] args)
{
double[] a = {0.75, 0.5, 1.0};
sort(a);
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
public static void sort(double[] tal)
{
double p = 0;
int k = 0;
for (int i = 0; i < tal.length - 1; i++)
{
k = i;
for (int j = i + 1; j < tal.length; j++)
{
if (tal[j] < tal[k])
k = j;
}
p = tal[i];
tal[i] = tal[k];
tal[k] = p;
}
}
At first, I incorrectly thought it an Insertion sort. It is a Selection sort (from the Wikipedia entry)
It is a selection sort. The inner loop finds the smallest among the remaining elements which is then exchanged with the first element of the unsorted range.
It's selection sort. Insertion sort works with a forand a while loop.
Related
So I have done a Bucket Sort algorithm that works just fine, but now I'm being asked to do it recursively. The Bucket Sort itself is something along the lines of:
public static void bucketSort(int[] arr, int max) {
int[] bucket = new int[max + 1];
for (int i = 0; i < arr.length; i++) {
bucket[arr[i]]++;
}
int x = 0;
for (int i = 0; i < bucket.length; i++) {
for (int j = 0; j < bucket[i]; j++) {
arr[x++] = i;
}
}
}
So my question would be, how to make this same algorithm but recursively?
Note: I'm coding in Java using IntelliJ, but feel free to explain in other languages if you prefer it.
Thanks in advance!
Hi I'm trying to figure out how to use BubbleSort in Java and my code is erroring and I don't know why
import java.util.ArrayList;
public class SortsRunner {
public static void BubbleSort(ArrayList<Integer> nums) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = arr.size();
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr.get(j) > arr.get(j+1))
{
int temp = arr.get(j);
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
}
}
public static void SelectionSort(ArrayList<Integer> nums) {
}
public static void printArrayList(ArrayList<Integer> nums) {
for(int i = 0; i < nums.size(); i++) {
System.out.println(nums.get(i) + " ");
}
System.out.println();
}
public static ArrayList<Integer> makeRandomArrayList() {
ArrayList<Integer> nums = new ArrayList<>();
for(int i = 0; i < (int)(Math.random() * 11) + 5; i++) {
nums.add((int)(Math.random() * 100));
}
return nums;
}
public static void main(String[] args) {
printArrayList(makeRandomArrayList());
}
}
When I get to arr.get(j) = arr.get(j+1); and arr.get(j+1) = temp; the left side errors saying "The left-hand side of an assignment must be a variable." can anyone help me fix this?
arr.get(j) = arr.get(j+1);
arr.get(j+1) = temp;
You're trying to assign a value to the result of a method call.
You just can't do this. You can only assign to a local variable, a field in the current class, a field access (e.g. foo.bar = ...) or an array element (e.g. foo[0] = ...).
Instead, you should use set to update a list element:
arr.set(j, arr.get(j+1));
arr.set(j+1, temp);
For the specific case of swapping two elements around in a list, you can instead use Collections.swap:
Collections.swap(arr, j, j+1);
You are doing several things wrong.
The obivous get and set issues already mentioned.
The fact that your are sorting an empty list. You pass in nums but sort the one you create which is empty.
You should use a boolean to prevent unnecessary repeats of the outer loop. Think of it like this, if you don't make a swap on the first iteration of the outer loop, then you won't swap on subsequent iterations.
And one style suggestion. Don't use loops or if statements without {}. Even if they only contain a single line of code. You will be less likely to make coding errors if you do so.
Try the following:
public static void BubbleSort(List<Integer> nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
boolean swapped = false;
for (int j = 0; j < n-1; j++) {
if (nums.get(j) > nums.get(j + 1)) {
int temp = nums.get(j);
nums.set(j, nums.get(j + 1));
nums.set(j + 1, temp);
swapped = true;
}
}
if (!swapped) {
break;
}
}
}
I need to have an algorithm that changes values in one array if it is in the second array. The result is that the first array should not have any values that are in the second array.
The arrays are of random length (on average ranging from 0 to 15 integers each), and the content of each array is a list of sorted numbers, ranging from 0 to 90.
public void clearDuplicates(int[] A, int[] B){
for(int i = 0; i < A.length; i++){
for(int j = 0; j < B.length; j++)
if(A[i] == B[j])
A[i]++;
}
}
My current code does not clear all of the duplicates. On top of that it might be possible it will creat an index out of bounds, or the content can get above 90.
Although your question is not very clear, this might do the job. Assumptions:
The number of integers in A and B is smaller than 90.
The array A is not sorted afterwards (use Arrays.sort() if you wish to
fix that).
The array A might contain duplicates within itself afterwards.
public void clearDuplicates(int[] A, int[] B) {
// Initialize a set of numbers which are not in B to all numbers 0--90
final Set<Integer> notInB = new HashSet<>();
for (int i = 0; i <= 90; i++) {
notInB.add(i);
}
// Create a set of numbers which are in B. Since lookups in hash set are
// O(1), this will be much more efficient than manually searching over B
// each time. At the same time, remove elements which are in B from the
// set of elements not in B.
final Set<Integer> bSet = new HashSet<>();
for (final int b : B) {
bSet.add(b);
notInB.remove(b);
}
// Search and remove duplicates
for (int i = 0; i < A.length; i++) {
if (bSet.contains(A[i])) {
// Try to replace the duplicate by a number not in B
if (!notInB.isEmpty()) {
A[i] = notInB.iterator().next();
// Remove the added value from notInB
notInB.remove(A[i]);
}
// If not possible, return - there is no way to remove the
// duplicates with the given constraints
else {
return;
}
}
}
}
You can do it just by using int[ ] although it's a bit cumbersome. The only constraint is that there may not be duplicates within B itself.
public void clearDuplicates(int[] A, int[] B) {
//Number of duplicates
int duplicate = 0;
//First you need to find the number of duplicates
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++)
if (A[i] == B[j])
duplicate++;
}
//New A without duplicates
int[] newA = new int[A.length-duplicate];
//For indexing elements in the new A
int notDuplicate = 0;
//For knowing if it is or isn't a duplicate
boolean check;
//Filling the new A (without duplicates)
for (int i = 0; i < A.length; i++) {
check = true;
for (int j = 0; j < B.length; j++) {
if (A[i] == B[j]) {
check = false;
notDuplicate--;//Adjusting the index
}
}
//Put this element in the new array
if(check)
newA[notDuplicate] = A[i];
notDuplicate++;//Adjusting the index
}
}
public class DuplicateRemove {
public static void main(String[] args) {
int[] A = { 1, 8, 3, 4, 5, 6 };
int[] B = { 1, 4 };
print(clear(A, B));
}
public static int[] clear(int[] A, int[] B) {
int a = 0;
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
if (A[i] == B[j]) {
a++;
for (int k = i; k < A.length - a; k++) {
A[k] = A[k + 1];
}
}
}
}
int[] C = new int[A.length - a];
for (int p = 0; p < C.length; p++)
C[p] = A[p];
return C;
}
public static void print(int[] A) {
for (int i = 0; i < A.length; i++)
System.out.println("Element: " + A[i]);
}
}
Here is an example.. I compiled and its working. For any question just let me know :)
maybe you should try the following code:
public void clear (int[] A, int[] B)
{
for (int i=0; i<A.length;i++)
{
for (int j=0; j<B.length; j++)
if(A[i]==B[j])
{
for (int k=i; k<A.length;k++)
A[k]=A[k+1];
j=B.length-1; //so that the cycle for will not be executed
}
}
}
I am really new to java and having a bit of trouble with this. I have looked at other code on here and other places with similar problems but I do not understand the library files, etc. I'm trying to understand the basics now. Any help would be appreciated. My current code is:
public static void main(String[] args) {
double[][] father = new double[25][25];
for (int i = 0; i < 25; i++){
father[i] = Math.random();
for (int j = 0; j < 25; j++){
father[j] = Math.random();
}
}
I dont know java but a 2d array should work like this
public static void main(String[] args) {
double[][] father = new double[25][25];
for (int i = 0; i < 25; i++){
for (int j = 0; j < 25; j++){
father[i][j] = Math.random();
}
}
You are trying to set an array of doubles to a double. when trying to specify a certain item in the 2d array, always use arrayName[index1][index2].
public static void main(String[] args) {
double[][] father = new double[25][25];
for (int i = 0; i < 25; i++){
for (int j = 0; j < 25; j++){
father[i][j] = Math.random();
}
}
A two-dimensional array, such as you have, requires both indexes in order to refer to a specific element. For example father[3][6] is an element of the array (a double, because that's the type of the array), but father[i] is not.
Also, you should use the array lengths, not hard-coded values, as the iteration limits. That way, if the array's size changes, you don't need to change the limits as well. Instead of for (int i = 0; i < 25; i++) you should use for (int i = 0; i < father.Length; i++) so that if the length of the array changes you still iterate over the whole thing without overflowing.
All in all:
double[][] father = new double[25][25];
for (int i = 0; i < father.Length; i++) {
for (int j = 0; j < father[i].Length; j++) {
father[i][j] = Math.random();
}
}
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.