一日一プロ

挿入ソート

C++

#include <iostream>
#include <vector>

using namespace std;

int main(int argc, const char * argv[]) {
    
    int n;
    vector<int> data;
    
    cin >> n;
    
    for(int i=0; i < n; i++){
        int tmp;
        cin >> tmp;
        data.push_back(tmp);
    }
    
    for(int i=1; i<n; i++){
        int v = data[i];
        int j = i-1;
        while( (j >= 0) && (data[j] > v)){
            data[j+1] = data[j];
            j--;
        }
        data[j+1] = v;
        
        for(int k=0; k < n; k++){
            cout << data[k] << " ";
        }
        cout << endl;
    }
    return 0;
}

C#

using System;
using System.Collections.Generic;

namespace InsertSort
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			int N = int.Parse (Console.ReadLine ());
			List<int> data = new List<int> ();

			for (int i = 0; i < N; i++) {
				data.Add (int.Parse (Console.ReadLine ()));
			}

			for (int i = 1; i < data.Count; i++) {
				int v = data [i];
				int j = i - 1;
				while ((j >= 0) && (data [j] > v)) {
					data [j+1] = data [j];
					j--;
				}
				data [j+1] = v;

				for (int k = 0; k < data.Count; k++) {
					Console.Write ("{0} ", data [k]);
				}
				Console.Write ("\n");
			}
		}
	}
}
広告を非表示にする