Home > Java > Ascending Or Descending

Ascending Or Descending

Berikut dibawah ini contoh kode program pada java untuk mengurutkan nilai pada array secara ascending dan desceding

// Simpan file dengan nama TUKAR.java

class baseClass
{
private Integer [] arrayAscending;
private Integer [] arrayDescending;

public Integer[] getArrayDescending()
{
return arrayDescending;
}

public void setArrayDescending(Integer[] arrayDescending)
{
Integer [] nilai = arrayDescending;

for(int i=0;i<nilai.length;i++)
{
for(int elemen=0;elemen<nilai.length-1;elemen++)
{
if(nilai[elemen]<nilai[elemen+1])
{
Integer temp;
temp = nilai[elemen];
nilai[elemen]=nilai[elemen+1];
nilai[elemen+1] = temp;
}
}
}

this.arrayDescending = nilai;
}

public Integer[] getArrayAscending()
{
return arrayAscending;
}

public void setArrayAscending(Integer[] arrayAscending)
{
Integer [] nilai = arrayAscending;

for(int i=0;i<nilai.length;i++)
{
for(int elemen=0;elemen<nilai.length-1;elemen++)
{
if(nilai[elemen]>nilai[elemen+1])
{
Integer temp;
temp = nilai[elemen];
nilai[elemen]=nilai[elemen+1];
nilai[elemen+1] = temp;
}
}
}

this.arrayAscending = nilai;
}

}

public class TUKAR extends baseClass
{
public static void main(String [] ar)
{
Integer nilai[] = new Integer[5];

nilai[0] = 3;
nilai[1] = 10;
nilai[2] = 72;
nilai[3] = 4;
nilai[4] = 99;

baseClass objBaseClass = new baseClass();

objBaseClass.setKeterangan(“Ascending”);
System.out.println(objBaseClass.getKeterangan());
objBaseClass.setArrayAscending(nilai);

for(Integer data : objBaseClass.getArrayAscending())
System.out.println(data);

System.out.println(“======”);

objBaseClass.setKeterangan(“Descending”);
System.out.println(objBaseClass.getKeterangan());
objBaseClass.setArrayDescending(nilai);

for(Integer data : objBaseClass.getArrayDescending())
System.out.println(data);

}

}

Categories: Java
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: