JAVA: I created an applet that takes the array of numbers and sorts them into as
ID: 3667250 • Letter: J
Question
JAVA: I created an applet that takes the array of numbers and sorts them into ascending order. When I run the file, it prints it out both times in the ascending order, it doesn't show the original order.
Sort.java
import java.awt.Graphics;
import java.applet.Applet;
public class Sort extends Applet
{
int a[] = { 55, 25, 66, 45, 8, 10, 12, 89, 68, 37 };
public void paint(Graphics g)
{
print(g,"Data items in original orer",a,25,25);
sort();
print(g,"Data items in ascending order",a,25,55);
}
/* A Sorting method here. */
public void sort()
{
int i,j,t;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
if(a[i]<a[j]){
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
}
public void print(Graphics g, String head, int b[], int x, int y)
{
g.drawString(head,x,y);
x+=15;
y+=15;
for(int i=0;i<b.length;i++){
g.drawString(String.valueOf(b[i]),x,y);
x+=20;
}
}
}
SortLogic.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div> Hello </div>
<applet code="Sort.class" width=300 height=200>
</applet>
</body>
</html>
Explanation / Answer
The for loop should be as follows
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
in your method for every time the element compares with it only or else you can use the a.sort();
method to do directly to sort
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.