I was debugging my code and found a problem with my Selection Sort Algorithm.
The code below almost sorts it, but I cant understand why all of it is not sorted.
have tried everything but to no avail.
import java.util.Random;
public class Help
{
//private static int[] myarray=new int[20];
private static int[] array;
public static void main(String[] args)
{
array=new int[20];
fillArrayRandom(array);
sortAscending(array);
///This is the bit that does not do what it is meant to do!
for(int i=0;i<array.length;i++)
{
// System.out.printf("Testing %d%n",myarray[i]);
}
}
public static void fillArrayRandom(int[] array)
{
int i;
for(i=0;i<array.length;i++)
{
array[i]=getRandomNum();
}
}
public static int getRandomNum()``
{
Random num=new Random();
int TestNumber=num.nextInt(2000);
return TestNumber;
}
public static void sortAscending(int[] array)
{
int smallest;
for(int i=0;i<array.length-1;i++)
{
smallest=i;
for(int index=i+1;index<array.length;index++)
{
if(array[index]<array[smallest])
smallest =index;
swap(i,smallest);
}
System.out.printf("%d%n",array[i]);
}
}
public static void swap(int first,int second)
{
int temporary=array[first];
array[first]=array[second];
array[second]=temporary;
}
}
You need to swap after the inner loop has completed:
public static void sortAscending(int[] array)
{
int smallest;
for(int i=0;i<array.length-1;i++)
{
smallest=i;
for(int index=i+1;index<array.length;index++)
{
if(array[index]<array[smallest])
smallest =index;
}
if (i != smallest) swap(i,smallest);
System.out.printf("%d%n",array[i]);
}
}
Related
why should i use two swap functions in second and i only one swap function in first
//first one am getting correct answer with only one swap
import java.util.*;
public class stringper
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.next();
perm(s,0,s.length());
}
static void perm(String s,int left,int right)
{
if(left==right)
{
System.out.print(s+" ");
}
for(int i=left;i<right;i++)
{
s=swap(s,i,left,1);
perm(s,left+1,right);
}
}
static String swap(String s,int i,int j)
{
char ch[]=s.toCharArray();
char temp=ch[i];
ch[i]=ch[j];
ch[j]=temp;
s=new String(ch);
return s;
}
}
//in the second code am getting correct answer with two swap functions
import java.util.*;
public class stringper
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String s=sc.next();
int nums[]={1,2,3};
perm(nums,0,nums.length);
}
static void perm(int[] nums,int left,int right)
{
for(int k=0;k<nums.length;k++)
{
System.out.print(nums[k]);
}
System.out.print(" ");
if(left==right)
{
ArrayList<Integer> l1=new ArrayList<Integer>();
for(int i=0;i<nums.length;i++)
{
//l1.add(nums[i]);
}
//l.add(l1);
}
for(int i=left;i<right;i++)
{
nums=swap(nums,i,left);
perm(nums,left+1,right);
nums=swap(nums,i,left);
}
}
static int[] swap(int[] nums,int i,int j)
{
int temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
for(int k=0;k<nums.length;k++)
{
nums[k]=nums[k];
}
return nums;
}
}
I want to make a thread which will sort an array with the BubbleSort method, but I have some problems.
This is my BubbleSort class:
package thread;
import java.util.Arrays;
public class BubbleSort implements Runnable {
private int[] array;
private long start, end;
public BubbleSort(int[] array){
this.array=array;
}
public void sort(){
int j;
boolean flag = true;
int temp;
while (flag) {
flag= false;
for( j=0;j<array.length-1;j++ ){
if (array[j]>array[j+1]){
temp = array[ j ];
array[j] = array[ j+1 ];
array[j+1] = temp;
flag=true;
}
}
}
}
#Override
public void run() {
start = System.currentTimeMillis();
this.sort();
end = System.currentTimeMillis();
System.out.println(end-start);
}
public long getTime(){
return end - start;
}
#Override
public String toString(){
return Arrays.toString(array);
}
}
and the main class:
package multisort;
import thread.BubbleSort;
public class MultiSort {
public static void main(String[] args) {
int[] x = {12,34,53,1,23,532,102,31,12,0,344,123,5422,12341,22,3410,123,342,233,12342,234432,12334};
BubbleSort bs = new BubbleSort(x);
Thread bsThread = new Thread(bs);
bsThread.start();
System.out.println(bs+"\n"+bs.getTime());
/*
bs.sort();
System.out.println(bs); it works
*/
}
}
The problem is that the array will not be sorted if I call my sort method in the run method. Who can help me with a response?
You don't wait for the thread to finish sorting. You just stomp on the array regardless of what the other thread is doing!
This is like telling your daughter she can use the car and then opening the hood and taking out bits of the motor.
package interf;
public class NumberPrinter {
public interface Printer {
public void print (int idx);
}
public static void print (Printer p) {
for (int i = 0; i < 4; i++) {
p.print(i);
}
}
public static void main(String[] args) {
while(true){
System.out.println("hi-1");
print(new Printer() {
#Override
public void print(int idx) {
while(true){
System.out.println(idx);
}
}
});
}
}
}
why it only printing 0 0 0
why it is not printing System.out.println("hi-1");
The code (when fixed to make system System) prints "hi-1" then lots of 0's (forever), because your inner print method has a while(true) loop in it.
The outer while(true) loop is never executed more than once because your code gets "stuck" in this inner loop, so you never see "hi-1" more than once.
Comment out the second while loop and capitalize the first letter of system.out.println and you'll get an infinite loop of:
hi-1
0
1
2
3
hi-1
0
1
2
3
...
package interf;
public class NumberPrinter {
public interface Printer {
public void print (int idx);
}
public static void print (Printer p) {
for (int i = 0; i < 4; i++) {
p.print(i);
}
}
public static void main(String[] args) {
while(true){
System.out.println("hi-1");
print(new Printer() {
#Override
public void print(int idx) {
//while(true){
System.out.println(idx);
//}
}
});
}
}
}
my issue is in my "NumberAnalyzer.java" class, I'm supposed to be able to use the "Number.java" class to determine if a number from the ArrayList is odd (as well as even and perfect later on) but since the "isOdd()" method in "Number.java" doesn't read in an int or other variable itself, I can't find a way to test each number to make "oddCount" in the "countOdds" method of "NumberAnalyzer.java" increase to produce the number of odd numbers in the string from the runner class.
NumberAnalyzer.java
import java.util.ArrayList;
import java.util.Scanner;
import com.sun.xml.internal.ws.api.pipe.NextAction;
import static java.lang.System.*;
public class NumberAnalyzer
{
private ArrayList<Number> list;
public NumberAnalyzer()
{
}
public NumberAnalyzer(String numbers)
{
list = new ArrayList<Number>();
String nums = numbers;
Scanner chopper = new Scanner(nums);
while(chopper.hasNext()){
int num = chopper.nextInt();
list.add(new Number(num));
}
chopper.close();
System.out.println(list);
}
public void setList(String numbers)
{
list = new ArrayList<Number>();
String nums = numbers;
Scanner chopper = new Scanner(nums);
while(chopper.hasNext()){
int num = chopper.nextInt();
list.add(new Number(num));
}
chopper.close();
}
public int countOdds()
{
int oddCount=0;
for(int i = 0; i < list.size(); i++){
if(Number.isOdd()== true){
oddCount++;
}
}
return oddCount;
}
public int countEvens()
{
int evenCount=0;
return evenCount;
}
public int countPerfects()
{
int perfectCount=0;
return perfectCount;
}
public String toString( )
{
return "";
}
}
Number.java
public class Number
{
private Integer number;
public Number()
{
}
public Number(int num)
{
number = num;
}
public void setNumber(int num)
{
number = num;
}
public int getNumber()
{
return number;
}
public boolean isOdd()
{
if(number%2==0){
return false;
}
return true;
}
public boolean isPerfect()
{
int total=0;
for(int i = 1; i < number; i++){
if(number%i==0){
total+= i;
}
}
return (number==total);
}
public String toString( )
{
String output = getNumber() + "\n" + getNumber()+ "isOdd == " + isOdd() + "\n" + getNumber()+ "isPerfect==" + isPerfect()+ "\n\n";
return output;
}
}
runner class
import java.util.ArrayList;
import java.util.Scanner;
import static java.lang.System.*;
public class Lab16b
{
public static void main( String args[] )
{
NumberAnalyzer test = new NumberAnalyzer("5 12 9 6 1 4 8 6");
out.println(test);
out.println("odd count = "+test.countOdds());
out.println("even count = "+test.countEvens());
out.println("perfect count = "+test.countPerfects()+"\n\n\n");
//add more test cases
}
}
When you call
test.countOdds());
control goes to NumberAnalyzer.java
public int countOdds()
{
int oddCount=0;
for(int i = 0; i < list.size(); i++){
if(Number.isOdd()== true){
oddCount++;
}
}
return oddCount;
}
And here you are calling Number.isOdd() method by Class name as a static way but i do not think you can do this way because isOdd() is not static.
It is compile time error
Solution:
Iterate your list and send value one by one from the list to isOdd(int val) method.
Try to make isOdd() method static which accept one numeric parameter and will return true or false.
increase your counter based on return type as you do.
The below program should display subsets where elements are separated by '|'. Here i am using static String array allocation. But it doesn't show output for array size >19. It did not throw exception. How to resolve this?
class kkk
{
static int set[]={3,4,9,14,15,19,28,37,47,50,54,56,59,61,70,73,78,81,92,95,97,99};
static int arr_size=(int)Math.pow((double)2,(double)set.length);
static String []abc=new String[arr_size+10];
static String wwf="";
static void subset(int x)
{
if(abc[0].equals("END"))
{
abc[0]=""+x;
}
else
{
int i,len=0,count=0;
for(i=0;i<abc.length;i++)
{
if(!abc[i].equals("END")){len=len+1;}
}
count=len;
wwf="";
for(i=0;i<len;i++)
{
wwf=abc[i];
wwf=wwf+"|"+x;
abc[count]=wwf;
count++;
}
abc[count]=""+x;
}
}
static void sub()
{
int len=set.length,i;
for(i=0;i<len;i++)
{
subset(set[i]);
}
int count=0;
for(i=0;i<abc.length;i++)
{
System.out.println("count:"+count+++"-----"+abc[i]);
}
}
public static void main(String args[])
{
for(int i=0;i<abc.length;i++)
{
abc[i]="END";
}
sub();
}
}
For ivanovic: Whats the output of the following program?
class kkk
{
static int valid_subset()
{
int count=0,len=abc.length,subset_count=0;
for(int i=0;i<len;i++)
{
if(!abc[i].equals("END"))
{
count=count+1;
}
}
String www="";
for(int i=0;i<count;i++)
{
int temp_large=0,sum=0,x=0;
www=abc[i];
String fgr="";
for(int j=0;j<www.length();j++)
{
if(!(""+www.charAt(j)).equals("|"))
{
fgr=fgr+www.charAt(j);
x=Integer.parseInt(fgr);
}
else
{
if(x>temp_large)
{
temp_large=x;
}
fgr="";
}
}
if(x>temp_large)
{
temp_large=x;
}
fgr="";
for(int j=0;j<www.length();j++)
{
if(!(""+www.charAt(j)).equals("|"))
{
fgr=fgr+www.charAt(j);
x=Integer.parseInt(fgr);
}
else
{
if(x!=temp_large)
{
sum=sum+x;
}
fgr="";
}
}
if(x!=temp_large)
{
sum=sum+x;
}
if(temp_large==sum)
{
subset_count=subset_count+1;
}
}
return subset_count;
}
static int set[]={3,4,9,14,15,19,28,37,47,50,54,56,59,61,70,73,78,81,92,95,97,99};
static int arr_size=(int)Math.pow((double)2,(double)set.length);
static String []abc=new String[arr_size+10];
static String wwf="";
static void subset(int x)
{
if(abc[0].equals("END"))
{
abc[0]=""+x;
}
else
{
int i,len=0,count=0;
for(i=0;i<abc.length;i++)
{
if(!abc[i].equals("END")){len=len+1;}
}
count=len;
wwf="";
for(i=0;i<len;i++)
{
wwf=abc[i];
wwf=wwf+"|"+x;
abc[count]=wwf;
count++;
}
abc[count]=""+x;
}
}
static void sub()
{
int len=set.length,i;
for(i=0;i<len;i++)
{
subset(set[i]);
}
/*int count=0;
for(i=0;i<abc.length;i++)
{
System.out.println("count:"+count+++"-----"+abc[i]);
}*/
}
public static void main(String args[])
{
for(int i=0;i<abc.length;i++)
{
abc[i]="END";
}
sub();
System.out.println(valid_subset());
}
}
Your looping over i, but not using i in the expression on line 28.
Change line 28 from:
if(!abc[0].equals("END")){len=len+1;}
to
if(!abc[i].equals("END")){len=len+1;}