.NET C#,VB.NET,VC.NET

■配列の要素を並び替え

配列の要素を並び替えるサンプルです。

System.Array.Sortメソッドを呼び出す方法が最も簡単ですが
並び替えの条件を自作することも可能です。

サンプルは両方の方法で同じ結果を出すコードです。
10個の整数を昇順に並び替えて出力します。

C#
using System;
using System.Collections;

namespace hello
{
    // Sort用クラス
    public class CSort : IComparer  
    {
        int IComparer.Compare( Object x, Object y )  
        {
            // 昇順に並べ替えます(MSDNのサンプルより)
            // 降順にする場合はxとyをひっくりかえします。
            return( (new CaseInsensitiveComparer()).Compare( x, y ) );

            // 以下のように自分で大小比較のロジックを書くことも可能。
            // この場合も上記と結果は同じ昇順になります。
            //        戻り値:0        xとyが等しい
            //        戻り値:正の数    xが大きい
            //        戻り値:負の数    yが大きい
//            if ( (int)x == (int)y )
//                return 0;
//            else if ( (int)x > (int)y )
//                return (int)1;
//            else
//                return (int)-1;
        }
    }

    class Class1
    {
        /// <summary>
        /// アプリケーションのメイン エントリ ポイントです。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // 並べ替えるデータが格納された配列
            int [] array = { 3, 8, 2, 1, 0, 9, 7, 5, 4, 6 };

            // 並べ替えた結果を格納するworkエリア
            int [] work;

            //---------------------------------------------------------
            // 昇順Sort
            //---------------------------------------------------------
            work = (int[])array.Clone();        // arrayの複製をworkへ
            System.Array.Sort(work);
            Put( "昇順Sort", ref work );

            //---------------------------------------------------------
            // Sort用メソッドを用意し、それのルールに従ってSortする場合
            //---------------------------------------------------------
            IComparer comp = new CSort();        // ソート用クラスのインスタンス作成
            work = (int[])array.Clone();        // arrayの複製をworkへ
            System.Array.Sort(work, comp );
            Put( "Sort用メソッドの場合", ref work );
        }

        static void Put( string prm_strTitle, ref int[] prm_array )
        {
            Console.WriteLine( prm_strTitle );
            foreach( int data in prm_array )
                Console.Write( "{0} ", data );
            Console.Write( "\r\n" );
        }
    }
}
VB.NET
Imports System
Imports System.Collections

Module Module1
    Public Class CSort
        Implements IComparer

        Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
           Implements IComparer.Compare

            ' 昇順に並べ替えます(MSDNのサンプルより)
            ' 降順にする場合はxとyをひっくりかえします。
            Return New CaseInsensitiveComparer().Compare(x, y)

            ' 以下のように自分で大小比較のロジックを書くことも可能。
            ' この場合も上記と結果は同じ昇順になります。
            '        戻り値:0        xとyが等しい
            '        戻り値:正の数    xが大きい
            '        戻り値:負の数    yが大きい
            'If x = y Then
            '    Return 0
            'ElseIf x > y Then
            '    Return 1
            'Else
            '    Return -1
            'End If
        End Function

    End Class

    Sub Main()
        ' 並べ替えるデータが格納された配列
        Dim array() As Integer = {3, 8, 2, 1, 0, 9, 7, 5, 4, 6}

        ' 並べ替えた結果を格納するworkエリア
        Dim work() As Integer

        '---------------------------------------------------------
        ' 昇順Sort
        '---------------------------------------------------------
        work = array.Clone()                ' arrayの複製をworkへ
        System.Array.Sort(work)
        Put("昇順Sort", work)

        '---------------------------------------------------------
        ' Sort用メソッドを用意し、それのルールに従ってSortする場合
        '---------------------------------------------------------
        Dim comp As IComparer = New CSort   ' ソート用クラスのインスタンス作成
        work = array.Clone()                ' arrayの複製をworkへ
        System.Array.Sort(work, comp)
        Put("Sort用メソッドの場合", work)
    End Sub

    Sub Put(ByVal prm_strTitle As String, ByRef prm_array As Integer())
        Console.WriteLine(prm_strTitle)
        For Each data As Integer In prm_array
            Console.Write("{0} ", data)
        Next
        Console.Write(ControlChars.CrLf)
    End Sub
End Module
VC.NET
#include "stdafx.h"

#using <mscorlib.dll>

using namespace System;
using namespace System::Collections;

// Sort用クラス
public __gc class CSort : public IComparer  
{
    int IComparer::Compare( Object* x, Object* y )  
    {
        // 昇順に並べ替えます(MSDNのサンプルより)
        // 降順にする場合はxとyをひっくりかえします。
        return( (new CaseInsensitiveComparer())->Compare( x, y ) );

        // 以下のように自分で大小比較のロジックを書くことも可能。
        // この場合も上記と結果は同じ昇順になります。
        //        戻り値:0        xとyが等しい
        //        戻り値:正の数    xが大きい
        //        戻り値:負の数    yが大きい
        //Int32 vx = *dynamic_cast<__box Int32*>(x);
        //Int32 vy = *dynamic_cast<__box Int32*>(y);
        //if ( vx == vy )
        //    return 0;
        //else if ( vx > vy )
        //    return 1;
        //else
        //    return -1;
    }
};

void Put( String* prm_strTitle, Int32 prm_array[] )
{
    Console::WriteLine( prm_strTitle );
    for ( int i = 0; i < prm_array->Length; i++ )
        Console::Write( "{0} ", prm_array[i].ToString() );
    Console::Write( "\r\n" );
}

int _tmain()
{
    // 並べ替えるデータが格納された配列
    Int32 array[] = { 3, 8, 2, 1, 0, 9, 7, 5, 4, 6 };

    // 並べ替えた結果を格納するworkエリア
    Int32 work[];

    //---------------------------------------------------------
    // 昇順Sort
    //---------------------------------------------------------
    work = dynamic_cast<Int32[]>(array->Clone());    // arrayの複製をworkへ
    System::Array::Sort(work);
    Put( S"昇順Sort", work );

    //---------------------------------------------------------
    // Sort用メソッドを用意し、それのルールに従ってSortする場合
    //---------------------------------------------------------
    IComparer *comp = new CSort();                    // ソート用クラスのインスタンス作成
    work = dynamic_cast<Int32[]>(array->Clone());    // arrayの複製をworkへ
    System::Array::Sort(work, comp );
    Put( S"Sort用メソッドの場合", work );

    return 0;
}
【実行結果】
昇順Sort
0 1 2 3 4 5 6 7 8 9
Sort用メソッドの場合
0 1 2 3 4 5 6 7 8 9

トップ  > .NET C#,VB.NET,VC.NET
Copyright (C) 2005.09 〜 By Shougo Suzaki

SEO [PR] 爆速!無料ブログ 無料ホームページ開設 無料ライブ放送