So I have this code for my selection sort:
public static void selectionSort(int[] arrayToSort){
int smallest;
for(int i = 0; i < arrayToSort.length; i++){
smallest = i;
for(int j = i+1; j < arrayToSort.length; j++){
if(arrayToSort[j] < arrayToSort[smallest]){
smallest = j;
}
if(smallest != i){
int temp = arrayToSort[i];
arrayToSort[i] = arrayToSort[smallest];
arrayToSort[smallest] = temp;
}
}
}
}
I am generating a int array with random numbers. My selection sort sometimes does sort the array, sometimes it does "almost" sort the array. The array will mostly be sorted except for a very few numbers which are in wrong places. I can't figure out what goes wrong here, any ideas?
Some test results where the array were not completely sorted:
***NON SORTED***
77
53
27
58
83
***SORTED***
27
53
77
58
83
and
***NON SORTED***
40
87
27
48
82
***SORTED***
27
40
82
48
87
You have a part of code inside the inner loop, put it outside the loop;
public static void selectionSort(int[] arrayToSort){
int smallest;
for(int i = 0; i < arrayToSort.length; i++){
smallest = i;
for(int j = i+1; j < arrayToSort.length; j++){
if(arrayToSort[j] < arrayToSort[smallest]){
smallest = j;
}
}
if(smallest != i){
int temp = arrayToSort[i];
arrayToSort[i] = arrayToSort[smallest];
arrayToSort[smallest] = temp;
}
}
}
See for instance the algorithm in Wikipedia.
I did this when i need it in college project !
references : selection algoritm with figure
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;
}
}
Here inside 2nd foor loop, if you find any elements which is less than i(or smallest) you are doing swap operation which is not required here. In selection sort, you need to get smallest element from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array.
Just keep swap outside of 2nd inner loop So that it only does swap operation for smallest element.
for(int i = 0; i < arrayToSort.length; i++){
smallest = i;
for(int j = i+1; j < arrayToSort.length; j++){
if(arrayToSort[j] < arrayToSort[smallest]){
smallest = j;
}
}
if(smallest != i){
int temp = arrayToSort[i];
arrayToSort[i] = arrayToSort[smallest];
arrayToSort[smallest] = temp;
}
}
Related
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;
}
So let's say I have an array that is {4 -2 1 2 3 -8 6 7 10 12}: I put it through this method to get a pair that adds up to a target number such as 10.
static int[] getCandidatePair(int A[], int target) {
int []pair = {0,0};
int size = A.length;
for (int j = 0; j < size; j++) {
for (int i = 0; i < size; i++){
if (A[i]+ A[j] == target) {
pair[0] = A[i];
pair[1]= A[j];
}//end if
}//end for i
}//end for j
return pair;
}//end get method
How do I make the outputted pair (4,6) instead of the (-2,12). I'm thinking I may have to sort the array in this function too?
static int[] getCandidatePair(int A[], int target) {
int []pair = {0,0};
int size = A.length;
for (int j = 0; j < size; j++) {
for (int i = 0; i < size; i++){
if ((A[i] + A[j]) == target) {
pair[0] = A[i];
pair[1]= A[j];
return pair;
}//end if
}//end for i
}//end for j
return pair;
}//end get method
Based on the information you provided, this might solve your problem. What was happening first was that your method wasn't returning the first pair it matched. This is because there was not a return statement in your if statement block. Hence, it missed the (4,6) pair and returned the last pair numbers which matched according to your input.
The problem is to count how many times my bubble sort algorithm switches the places of numbers. I tried to use a variable which increments by one each time, but I think there may be an error with scopes or something similar. Instead of returning a number such as 6 (which means numbers were swapped 6 times), it returns 0, which is what I initialized my variable as. How would I get my program to work?
public static int sort(int arr[]) {
int length = arr.length;
int temp;
int count = 0;
for (int i = 0; i < (length); i++) {
for (int j = 1; j < (length); j++) {
if (arr[j - 1] > arr[j]) {
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
count++;
}
}
}
return count;
}
Looks like your algorithm is not optimized because of your for loop condition and initialization. As a result you are comparing an element with itself which is redundant.
Proper approach should be like below:
int yourCounter = 0;
for (int i = 0; i < length; i++)
for (int j = 1; j < length-i; j++)
if (arr[j - 1] > arr[j]) {
//swap code
//yourCounter++;
}
your counter should give you proper result then.
I have this function for selection sort:
public static void selectionSort(int[] n)
{
for(int start = 0; start < n.length; start++)
{
int smallest = start;
for(int i = start+1; i<n.length; i++)
{if(n[i]<n[start])
smallest = i;}
int tmp = n[start];
n[start] = n[smallest];
n[smallest] = tmp;
}
}
and i call it like this.
Random ran = new Random();
int n = 10;
int[] a = new int[n];
for(int i = 0; i<n; i++)
a[i] = ran.nextInt(1000);
However, it causes results like this..
640 900 610 168 650 610 527 356 802 486
486 640 356 168 610 527 610 650 802 900
the top one is not sorted the lower one is supposed to be sorted. However, it is not correct.
You are comparing the initial start index every singe iteration, even if you have found a smaller number you are still comparing it to the original start which should not happen. Once you find a smaller number you need to use that index for the comparison.
To compare it to the smallest number every iteration change (n[i]<n[start]) to (n[i]<n[smallest]) and that will fix your problem.
Hope this helps!
The second loop is useless because you are comparing, after all, just the first and the last item and smallest takes it's value from this comparison only.
By your code I guess you're trying to do a Bubble Sort, but the comparison and the index management is wrong, here is a posible solution:
public static void main(String[] args) {
Random ran = new Random();
int n = 10;
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = ran.nextInt(1000);
}
printArray(array);
selectionSort(array);
printArray(array);
}
private static void printArray(int[] array) {
System.out.print("Array: ");
for (int i : array) {
System.out.print(i + " ");
}
System.out.println();
}
private static void selectionSort(int[] array) {
for (int j = 0; j < array.length; j++) {
// Subtract 1 so you don't get a NullPointerException
// Subtract j so you don't compare the numbers already ordered
for (int i = 0; i < array.length - 1 - j; i++) {
if (array[i] > array[i + 1]) {
int tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
}
}
}
}
The algorithm is taken from the Spanish version (I'm from Argentina) of the link above, which is also in the English version with other notation.
Hope this helps. Best regards
Try to use this version of code it's functional:
public static void main(String[] args) {
Random ran = new Random();
int n = 10;
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ran.nextInt(1000);
selectionSort(a);
for (int i : a) {
System.out.print(i+" ");
}
}
public static void selectionSort(int[] n)
{
for(int start = 0; start < n.length-1; start++)
{
int smallest = start;
for(int i = start+1; i<n.length; i++)
{if(n[i]<n[smallest])
smallest = i;}
int tmp = n[start];
n[start] = n[smallest];
n[smallest] = tmp;
}
}
This is the assignment: Write a method that sorts the elements of a matrix with 2 dimensions. For example
sort({{1,4}{2,3}})
would return a matrix
{{1,2}{3,4}}.
I dont know what im doing wrong in my code cause the output i get is 3.0, 3.0, 4.0, 4.0.
This is what i have so far any help would be appreciated.
public static void main(String[] args) {
double[][] array = { {1, 4}, {2, 3} };
double[][] new_array = sort(array);
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length; j++) {
System.out.print(new_array[i][j] + " ");
}
}
}
public static double[][] sort(double[][] array) {
double[] storage = new double[array.length];
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length; j++) {
storage[i] = array[i][j];
}
}
storage = bubSort(storage);
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length; j++) {
array[i][j] = storage[i];
}
}
return array;
}
public static double[] bubSort(double[] list) {
boolean changed = true;
double temp;
do {
changed = false;
for (int j = 0; j < list.length -1; j++)
if (list[j] > list[j + 1]) {
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
changed = true;
}
} while (changed);
return list;
}
}
The main problem that you are experiencing is how you are copying the values from the 2d array into the 1d array. You are actually only copy two values into an array of length 2. The length of a 2d array is not the full m x n length.
I will give a small hint how you can go about copying from the 2d array into the 1d array, but it is up to you to figure out how to copy back from the 1d array into the 2d array. Also, how would you go about finding the full length of the array?
double[] storage = new double[4];//You should calculate this value
int k = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
storage[k++] = array[i][j];
}
}
Your bubble sort works fine, but then you are copying the values back wrong. Try printing the array storage after the sort and you will see that it is now correct.
You are overwriting your storage array you have it set to array[i]. Because it is in the for loop you are setting storage[0] = array[0][0] then setting storage[0] = array[0][1]. This causes you to only pick up the last number in that dimension of the array. Likewise, when you are reading them back out you are inserting the same number twice. Since 4 and 3 are the last two numbers in their respective dimensions this shows that you are sorting the array. You need a for loop for storage that is set < array.length and store your values inside that.