How to do Sorting of number using bubble sort in asp.net ?


Sort
Hi

There are so many approach to do sorting of number like quick sort,bubble sort, Heap Sort, and Merge sort

If you want to read more details about this then please refer this artical

Sorting Algorithm in C#

Bubble sort is one of the simple sort algorithm, In this algorithm we have to compare each two unsorted number, if the value of first no is greater than second one then we have to swap the no.

In this algorithm we have take two loops. i.e Main loop and nested loop

main loop is used for no of passes and nested loop is used for no of comparisons.

Here you will also learn how to convert string array to integer array in C#

Complete code in C# will be like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

       
        
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string s = txtNum.Text;

        int[] num = s.Split(',').Select(str => int.Parse(str)).ToArray();

        for (int i = 0; i < num.Length - 1; i++)
        {
            for (int j = 0; j < num.Length - 1; j++)
            {
                if (num[j] > num[j + 1])
                {
                    int temp;
                    temp = num[j + 1];
                    num[j + 1] = num[j];
                    num[j] = temp;
                }

            }

        }

        for (int k = 0; k < num.Length; k++)
        {
            lblmsg.Text += num[k].ToString() +" ";
        }
    }
}

Summary

This artical include

1. How to do sorting using bubble sort
2. How to convert string array to Integer array in above code.

Advertisements

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