[Java] Sorting A Three-Valued Sequence

Sorting a Three-Valued Sequence

Sorting is one of the most frequently performed computational tasks. Consider the special sorting problem in which the records to be sorted have at most three different key values. This happens for instance when we sort medalists of a competition according to medal value, that is, gold medalists come first, followed by silver, and bronze medalists come last.

In this task the possible key values are the integers 1, 2 and 3. The required sorting order is non-decreasing. However, sorting has to be accomplished by a sequence of exchange operations. An exchange operation, defined by two position numbers p and q, exchanges the elements in positions p and q.

You are given a sequence of key values. Write a program that computes the minimal number of exchange operations that are necessary to make the sequence sorted.

PROGRAM NAME: sort3

INPUT FORMAT

Line 1: N (1 <= N <= 1000), the number of records to be sorted
Lines 2-N+1: A single integer from the set {1, 2, 3}

SAMPLE INPUT (file sort3.in)

9
2
2
1
3
3
3
2
3
1

OUTPUT FORMAT

A single line containing the number of exchanges required

SAMPLE OUTPUT (file sort3.out)

4

/* Use the slash-star style comments or the system won't see your
   identification information */
/*
ID: lincans1
LANG: JAVA
TASK: sort3
*/
import java.io.*;
import java.util.*;

public class sort3 {

	private void swap (int[] array, int a, int b) {
		int temp = array[a];
		array[a] = array[b];
		array[b] = temp;
	}

	private int count (int[] array) {
		int[] count = new int[4];
		for (int i : array) {
			count[i]++;
		}
		count[2] += count[1];
		count[3] += count[2];
		int one_three = 0, three_one = 0, sum = 0;
		for (int i = 0, n = count[1]; i < n; i++) {
			if (array[i] == 3) {
				one_three++;
			}
		}
		for (int i = count[1], n = count[2]; i < n; i++) {
			if (array[i] != 2) {
				sum++;
			}
		}
		for (int i = count[2], n = count[3]; i < n; i++) {
			if (array[i] == 1) {
				three_one++;
			}
		}
		return Math.max(one_three, three_one) + sum;
	}

	public sort3() throws IOException {
		// Use BufferedReader rather than RandomAccessFile; it's much faster
		BufferedReader f = new BufferedReader(new FileReader("sort3.in"));
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("sort3.out")));

		int N = Integer.parseInt(f.readLine());
		int[] array = new int[N];
		for (int i = 0; i < N; i++) {
			array[i] = Integer.parseInt(f.readLine());
		}
		int ans = count(array);
		out.println(ans);
	    out.close();
	    f.close();
	}
	
	public static void main (String [] args) throws IOException {
		new sort3();
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值