日期:2014-05-20 浏览次数:21009 次
import java.util.Scanner;
public class duiProject {
public static void main(String[]args)throws Exception
{
int[]data=new int[2000];
input(data);
heap_sort(data);
}
public static void input(int[] data)throws Exception
{
java.io.File file1=new java.io.File("D:\\eclipse——workplace\\heapin.txt");
Scanner input=new Scanner(file1);
int i;
for(i=1;i<data.length;i++)
{
data[i]=input.nextInt();
}
input.close();
}
public static void output(int[] data, String str)throws Exception
{
java.io.File file2=new java.io.File("heapout.txt");
java.io.PrintWriter output=new java.io.PrintWriter(file2);
output.println(str);
for(int i=0; i<data.length; i++)
output.print(data[i] + " ");
output.println();
output.close();
}
public static void heap_sort(int []data)throws Exception
{
int n=data.length;
int temp=0;
output(data, "Before sort : ");
for(int i=n/2; i>0; i--)
Adjust(data, i-1, n);
for(int i=n-2; i>=0; i--)
{
temp = data[i+1];
data[i+1] = data[0];
data[0] = temp;
Adjust(data, 0, i+1);
}
output(data, "After sort : ");
}
public static void Adjust(int[] data, int i, int n)
{
int j = 0;
int temp = 0;
temp = data[i];
j = 2 * i + 1;
while(j <= n-1)
{
if(j < n-1 && data[j] < data[j+1])
j++;
if(temp >= data[j])
break;
data[(j-1)/2] = data[j];
j = 2 * j + 1;
}
data[(j-1)/2] = temp;
}
}